Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get java.util.Calendar from days since epoch

I have a variable containing the days since the epoch reference date of 1970-01-01 for a certain date.

Does someone know the way to convert this variable to a java.util.Calendar?

like image 314
Thizzer Avatar asked May 23 '11 07:05

Thizzer


2 Answers

Use the java.time classes in Java 8 and later. In one line:

LocalDate date = LocalDate.ofEpochDay(1000);

Calling ofEpochDay(long epochDay) obtains an instance of LocalDate from the epoch day count.

like image 153
Amit Ganguly Avatar answered Sep 20 '22 03:09

Amit Ganguly


The following should work:

Calendar c = new GregorianCalendar();
c.setTime(new Date(0));

c.add(Calendar.DAY_OF_YEAR, 1000);

System.err.println(c.getTime());

A note regarding time zones:

A new GregorianCalendar instance is created using the default time zone of the system the program is running on. Since Epoch is relative to UTC (GMT in Java) any time zone different from UTC must be handled with care. The following program illustrates the problem:

TimeZone.setDefault(TimeZone.getTimeZone("GMT-1"));

Calendar c = new GregorianCalendar();
c.setTimeInMillis(0);

System.err.println(c.getTime());
System.err.println(c.get(Calendar.DAY_OF_YEAR));

c.add(Calendar.DAY_OF_YEAR, 1);
System.err.println(c.getTime());
System.err.println(c.get(Calendar.DAY_OF_YEAR));

This prints

Wed Dec 31 23:00:00 GMT-01:00 1969
365
Thu Jan 01 23:00:00 GMT-01:00 1970
1

This demonstrates that it is not enough to use e.g. c.get(Calendar.DAY_OF_YEAR). In this case one must always take into account what time of day it is. This can be avoided by using GMT explicitly when creating the GregorianCalendar: new GregorianCalendar(TimeZone.getTimeZone("GMT")). If the calendar is created such, the output is:

Wed Dec 31 23:00:00 GMT-01:00 1969
1
Thu Jan 01 23:00:00 GMT-01:00 1970
2

Now the calendar returns useful values. The reason why the Date returned by c.getTime() is still "off" is that the toString() method uses the default TimeZone to build the string. At the top we set this to GMT-1 so everything is normal.

like image 24
musiKk Avatar answered Sep 23 '22 03:09

musiKk