Michael
Michael

Reputation: 1251

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

Upvotes: 6

Views: 7887

Answers (4)

Houcem Berrayana
Houcem Berrayana

Reputation: 3080

Please check in your control panel that you have not activated Summer's time. This bug may be because of this

Upvotes: 0

ssn771
ssn771

Reputation: 1270

November 6, 2011 was when daylight savings time ended in the US. So what you're seeing is the clock hit 2am on Nov 6th and then it rolls back to 1am to fall back an hour to standard time. So the offset also changes from -7 to -8 from GMT I believe for Pacific time. So it is working correctly from what I can see.

Upvotes: 2

Grzegorz Grzybek
Grzegorz Grzybek

Reputation: 6237

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.

Upvotes: 6

Sergii Zagriichuk
Sergii Zagriichuk

Reputation: 5399

I would advice you to use Gregorian chronology in Joda-Time

Upvotes: 1

Related Questions