Calendar and Daylight Savings Time

I'm trying to use Calendar objects to store month, day, year information for use in date comparisons/calculations. (e.g. how many days between 1/1/06 and 2/1/06) My program knows nothing of hours, seconds, minutes, etc. and it really doesn't care about them.

That being said, the concept of hour has been cropping up since Calendar automatically throws in an extra hour here and there for DST. In very specific circumstances it can cause an incorrect value.

So to solve this I decided to turn off DST but that seems to be more complicated than it should be. My solution was to create a SimpleTimeZone that has DST disabled and use that as the time zone in my Calendar. Unfortunately, this doesn't work. It now subtracts an hour every now and then (for some strange reason).

So is there any way I'm not seeing in the API to just simply disable DST?

Thanks in advance.

[901 byte] By [Kain222a] at [2007-11-26 18:50:26]
# 1
Possibly what you see is the result of something other than Calendar formatting the timestamp. Would you like to post a small example of your problem that we can criticize?
DrClapa at 2007-7-9 6:24:27 > top of Java-index,Java Essentials,Java Programming...
# 2

Ok here's a minimal example of what I'm taking about:

import java.util.GregorianCalendar;

import java.text.SimpleDateFormat;

public class Test {

public static void main( String[] args ) throws Exception {

SimpleDateFormat format = new SimpleDateFormat( "MM/dd/yy" );

format.setLenient( false );

GregorianCalendar testCal1 = new GregorianCalendar();

testCal1.setTime( format.parse( "10/29/2006" ) ); //One day before DST switch

GregorianCalendar testCal2 = new GregorianCalendar();

testCal2.setTime( format.parse( "10/30/2006" ) ); //After DST switch

long time1 = testCal1.getTimeInMillis();

long time2 = testCal2.getTimeInMillis();

System.out.println( time2 - time1 );

}

}

The output of the program is 90000000.

Using some basic math you can calculate that the time between a single day should be 86400000 milliseconds. The difference between the result and the theoretical time between two days is exactly 1 hour.

Kain222a at 2007-7-9 6:24:27 > top of Java-index,Java Essentials,Java Programming...
# 3

The SimpleDateFormat has a time zone built into it. When it parses a date it assumes that date is in that time zone. So you should just be using Date objects for your comparisons.

It isn't obvious to me why you care whether 2006-10-29 and 2006-10-30 are 23 or 24 or 25 hours apart, they are still in the same order regardless of that. But if you're building in an assumption that all dates are 24 hours apart then choose a timezone that doesn't use DST (America/Phoenix is one such and there are many others) and apply that to your SimpleDateFormat.

DrClapa at 2007-7-9 6:24:27 > top of Java-index,Java Essentials,Java Programming...
# 4
Thank you.
Kain222a at 2007-7-9 6:24:27 > top of Java-index,Java Essentials,Java Programming...