Java.util.Calendar - milliseconds since Jan 1, 1970

The dates you print from Calendar are local to your timezone, whereas the epoch is defined to be midnight of 1970-01-01 in UTC. So if you live in a timezone west of UTC, then your date will show up as 1969-12-31, even though (in UTC) it's still 1970-01-01.


First, c.get(Calendar.MONTH) returns 0 for Jan, 1 for Feb, etc.

Second, use DateFormat to output dates.

Third, your problems are a great example of how awkward Java's Date API is. Use Joda Time API if you can. It will make your life somewhat easier.

Here's a better example of your code, which indicates the timezone:

public static void main(String[] args) {

    final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);

    long l = 10000000L;
    System.out.println("Long value: " + l);
    Calendar c = new GregorianCalendar();
    c.setTimeInMillis(l);
    System.out.println("Date: " + dateFormat.format(c.getTime()));

    l = 1000000000000L;
    System.out.println("\nLong value: " + l);
    c.setTimeInMillis(l);
    System.out.println("Date: " + dateFormat.format(c.getTime()));
}

Calendar#setTimeInMillis() sets the calendar's time to the number of milliseconds after Jan 1, 1970 GMT.

Calendar#get() returns the requested field adjusted for the calendar's timezone which, by default, is your machine's local timezone.

This should work as you expect if you specify "GMT" timezone when you construct the calendar:

Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

Tags:

Java

Calendar