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.
source share