1

I want to get the year, month, date and hour from a long timestamp value. I found many examples of creating a Calendar from a timestamp value, but I don't get what I want.

I wrote the following

long timestamp = 1488866400;

Calendar cal = GregorianCalendar.getInstance();
cal.setTimeInMillis( timestamp );

System.out.println( cal.get( Calendar.YEAR ) );
System.out.println( cal.get( Calendar.MONTH ) );
System.out.println( cal.get( Calendar.DATE ) );

1488866400 is Tue, 07 Mar 2017 06:00:00 GMT, so I expected the code above to give me year 2017, month 2 and date 7, but it gives me year 1970, month 0 and day 17.

Can anyone tell me if I am doing anything wrong or if it could be made in a different way?

Adrián Juárez
  • 183
  • 5
  • 14
  • 1
    I cannot more strongly advise against using the legacy `java.util.Calendar` and `java.util.Date` classes. You should instead look at the `java.time` package for the class most appropriate for your use case. – Joe C Mar 07 '17 at 23:01
  • Please search Stack Overflow before posting. Most any basic date-time question has already been asked and answered. – Basil Bourque Mar 07 '17 at 23:09

2 Answers2

5

Multiply your timestamp by 1000. long timestamp = 1488866400 * 1000;

your timestamp is in seconds and calendar uses milliseconds

Giancarlo Benítez
  • 428
  • 1
  • 4
  • 19
0

Try this:

long timestamp = 1488866400;
LocalDate date = Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(date.getYear() );
System.out.println( date.getMonth() );
System.out.println( date.getDayOfMonth() );
Atul
  • 1,536
  • 3
  • 21
  • 37