Search code examples
javacalendar

Java Calendar class does not get correct date / time for a Unix timestamp of whole seconds


i use this code to convert a date-string into a unix timestamp:

int year = 2012;
int month = 2; // eg. for march
int day = 31;
int hrs = 0;
int min = 18;

this should represant this date/time 31.3.2012 00:18 or 3/31/2012 00:18 in english notation

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin")); // GMT+1
cal.set(year, month, day, hrs, min);
unixtime = cal.getTimeInMillis() / 1000;

The result of unixtime is: 1333145929 If i convert it back (cal.setTimeInMillis(1333145929 * 1000);) i got 30.3.2012 00:18

I lost one day!


Solution

  • How are you printing out the Calendar?

    I think you are getting the GMT time, which is one hour behind and therefore one day behind at midnight.

    Consider:

    public static void main(String[] args) throws Exception {
        int year = 2012;
        int month = 2; // eg. for march
        int day = 31;
        int hrs = 0;
        int min = 18;
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin")); // GMT+1
        cal.set(year, month, day, hrs, min);
        long time = cal.getTimeInMillis();
        System.out.println(time);
        cal.setTimeInMillis(time);
        final DateFormat sdf = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.FULL);
        System.out.println(sdf.format(cal.getTime()));
    }
    

    Output:

    1333145915825
    Friday, 30 March 2012 23:18:35 o'clock BST
    

    Now if I add in a TimeZone to the DateFormat:

    final DateFormat sdf = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.FULL);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
    System.out.println(sdf.format(cal.getTime()));
    

    I get:

    1333145887761
    Saturday, 31 March 2012 00:18:07 o'clock CEST
    

    So the SimpleDateFormat uses your default TimeZone when it formats and not the TimeZone of the Calendar (as you call Calendar.getTime()).