Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GregorianCalendar Timezone

I have a weird problem with a Java Gregorian Calendar:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S Z");
sdf.setTimeZone(TimeZone.getTimeZone("US/Pacific"));

GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("US/Pacific"));
cal1.setTimeInMillis(1320566400000L);

GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("US/Pacific"));
cal2.setTimeInMillis(1320570000000L);

System.out.println(sdf.format(cal1.getTime()));
System.out.println(sdf.format(cal2.getTime())); 

I executed the above given code on a machine with default timezone = US Pacific, but the machine is running in Germany.

The result is the following:

2011-11-06 01:00:00:0 -0700
2011-11-06 01:00:00:0 -0800

I really do not understand, why there is a different time zone in the result... I also tested the code on another machine (default Timezone = GMT) and it works correct.

Do somebody have an idea, why this problem occurs?

Best, Michael

like image 605
Michael Avatar asked Jun 14 '12 10:06

Michael


1 Answers

Add these lines to your program:

for (int i=0; i<24; i++) {
    cal1.add(Calendar.MINUTE, i*5);
    System.out.println(" : " + sdf.format(cal1.getTime()));
}

And you'll see:

 : 2011-11-06 01:00:00:0 -0700
 : 2011-11-06 01:05:00:0 -0700
 : 2011-11-06 01:15:00:0 -0700
 : 2011-11-06 01:30:00:0 -0700
 : 2011-11-06 01:50:00:0 -0700
 : 2011-11-06 01:15:00:0 -0800
 : 2011-11-06 01:45:00:0 -0800
 : 2011-11-06 02:20:00:0 -0800
 : 2011-11-06 03:00:00:0 -0800

So it seems you're changing summer time to winter time. My timezone is CET (UTC+01:00), so I can't tell why it's working on your second machine.

like image 60
Grzegorz Grzybek Avatar answered Sep 27 '22 22:09

Grzegorz Grzybek