Problem with Calendar/TimeZones

S

Silvia

Hi,

I habe a problem with setting HOUR_OF_DAY of my Calendar object to 0.
My method today() should give me a Date object containing today's date
in a configured timezone at 0:00 o'clock. Here is the code:

public Calendar getCalendarOfTimeZone() {
TimeZone timezone =
TimeZone.getTimeZone( Config.getProperty( "timezone" ) );
Calendar cal = Calendar.getInstance( timezone );
System.out.println( "### system time: " + cal.getTime() );
int offset = timezone.getOffset( cal.getTimeInMillis() );
cal.add( Calendar.MILLISECOND, offset );
System.out.println( "### adjusted time: " + cal.getTime() );
return cal;
}

public Date today() {
Calendar cal = getCalendarOfTimeZone();
System.out.println( "### time 1 : " + cal.getTime() );
cal.set( Calendar.HOUR_OF_DAY, 0 );
System.out.println( "### time 1 : " + cal.getTime() );
cal.clear( Calendar.HOUR_OF_DAY );
System.out.println( "### time 2 : " + cal.getTime() );
cal.clear( Calendar.MINUTE );
System.out.println( "### time 3 : " + cal.getTime() );
cal.clear( Calendar.SECOND );
System.out.println( "### time 4 : " + cal.getTime() );
return cal.getTime();
}

The output is:
### system time: Thu Jun 17 13:25:25 CEST 2004
### adjusted time: Thu Jun 17 06:25:25 CEST 2004
### time 0 : Thu Jun 17 06:25:25 CEST 2004
### time 1 : Wed Jun 16 09:25:25 CEST 2004
### time 2 : Wed Jun 16 09:25:25 CEST 2004
### time 3 : Wed Jun 16 09:00:25 CEST 2004
### time 4 : Wed Jun 16 09:00:00 CEST 2004

So, the adjusted time is correct (7 hours less than system time), but
while minutes and seconds are correctly set to 0, the hours are set to
the previous day at 09 hours. Why ???

Thanks for any help :eek:)
Silvia
 
T

Thomas Weidenfeller

Silvia said:
Hi,

I habe a problem with setting HOUR_OF_DAY of my Calendar object to 0.
My method today() should give me a Date object containing today's date
in a configured timezone at 0:00 o'clock. Here is the code:

Just a random guess (since the code you posted is not the code you used
for generating the output, I didn't feel inclined to look at it in detail):

You mixed up time zones. The time zone you are getting from your
property is not the default time zone (you didn't dare to tell us which
timezone it is, but I would bet it is nine or 15 hours away from your
default time zone). Since your print Date objects, you get printouts in
the default time zone.

/Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,218
Latest member
JolieDenha

Latest Threads

Top