Conversion from Unix Time to Java Calendar

Viewed 7542

The following is driving me crazy, why am I getting the wrong calendar date when converting Unix Time 1386230874 using the code below!!

This should be Thu Dec 5 19:07:54 2013

Output:

Comment posted on:Sat Jan 17 11:03:50 EST 1970

Code:

Calendar facebook_created_time_calendar = Calendar.getInstance(TimeZone.getTimeZone("Australia/Sydney"));    
facebook_created_time_calendar.setTimeInMillis(1386230874);
out.print("Comment posted on:");
out.println(facebook_created_time_calendar.getTime());
2 Answers

Java works with millisecond timestamps, while Unix time stamps are typically measured in seconds. Multiply the Unix timestamp by 1000L to get the right time.

Unix measures time as the number of seconds ("1386230" seconds [you went seconds to milliseconds with setTimeInMillis] is "16.04433" days) and since epoch (January 1, 1970 + 16.04 days is Jan 17 it is working) - so try this

facebook_created_time_calendar
    .setTimeInMillis(1386230874L * 1000);
Related