Get java.util.Calendar from days from era

I have a variable containing days from the reference date of the 1970-01-01 era to a specific date.

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

+4
source share
3 answers

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()); 

Time Zone Note:

A new instance of GregorianCalendar is created using the default time zone for the system on which the program is running. Since Epoch is UTC (GMT in Java), any time zone other than UTC should 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)); 

Will print

 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 insufficient use, for example. c.get(Calendar.DAY_OF_YEAR) . In this case, you must always consider what time of day it is. This can be avoided by using GMT explicitly when creating GregorianCalendar : new GregorianCalendar(TimeZone.getTimeZone("GMT")) . If the calendar is created in this way, the output will be as follows:

 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 the Date returned by c.getTime() still "off" is because the toString() method uses the default TimeZone to build the string. At the top, we set this to GMT-1, so everything is fine.

+2
source
 Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(0); cal.add(Calendar.DAY_OF_MONTH, daysSinceEpoch); 
+3
source

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

 LocalDate date = LocalDate.ofEpochDay(1000); 

The call ofEpochDay(long epochDay) receives an instance of LocalDate from the number of days of the era.

+3
source

All Articles