Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

calendar

Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what's wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same result.

public static void main(String[] args) {

    String x = "10000000";
    long l = new Long(x).longValue();
    System.out.println("Long value: " + l);

    Calendar c = new GregorianCalendar();
    c.setTimeInMillis(l);
    System.out.println("Calendar time in Millis: " + c.getTimeInMillis());

    String origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);  
    System.out.println("Date in YYYY-MM-DD format: " + origDate);

    x = "1000000000000";
    l = new Long(x).longValue();
    System.out.println("\nLong value: " + l);

    c.setTimeInMillis(l);
    System.out.println("Calendar time in Millis: " + c.getTimeInMillis());

    origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);  
    System.out.println("Date in YYYY-MM-DD format: " + origDate);
}

Long value: 10000000

Calendar time in Millis: 10000000

Date in YYYY-MM-DD format: 1969-11-31

Long value: 1000000000000

Calendar time in Millis: 1000000000000

Date in YYYY-MM-DD format: 2001-8-8

like image 257
Nathan Spears Avatar asked Nov 04 '08 20:11

Nathan Spears


2 Answers

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.

like image 117
Chris Jester-Young Avatar answered Sep 20 '22 01:09

Chris Jester-Young


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()));
}
like image 26
Steve McLeod Avatar answered Sep 22 '22 01:09

Steve McLeod