views:

215

answers:

1

I wanted to compare the current system date to a fix date, but get the wrong result. By trying to find out what's wrong, I ended with the following Java code:

    // today, 18th of August 2010
    long currSystem = System.currentTimeMillis();
    Calendar calToday = Calendar.getInstance();
    Calendar calFix = Calendar.getInstance();
    long milliToday = calToday.getTimeInMillis();
    long milliOlder = calFix.getTimeInMillis();
    long deltaOlder = milliOlder - milliToday;
    long deltaSystem = currSystem - milliToday;

    // 1st of August 2010
    calFix.set( 2010, 8, 1 );
    long milliChanged1 = calFix.getTimeInMillis();
    long deltaChanged1 = milliChanged1 - milliToday;
    boolean isAfter1 = calToday.after( calFix );
    boolean isBefore1 = calToday.before( calFix );

    // 1st of October 2010
    calFix.set( 2010, 10, 1 ); 
    long milliChanged2 = calFix.getTimeInMillis();
    long deltaChanged2 = milliChanged2 - milliToday;
    boolean isAfter2 = calToday.after( calFix );
    boolean isBefore2 = calToday.before( calFix );

The results in the debugger are:

currSystem: 1282160371775
deltaChanged1: 1209600009
deltaChanged2: 6480000009
deltaOlder: 9
deltaSystem: -25
isAfter1: false
isAfter2: false
isBefore1: true isBefore2: true milliChanged1: 1283369971809
milliChanged2: 1288640371809
milliOlder: 1282160371809
milliToday: 1282160371800

The small differences for deltaOlder and deltaSystems are due to the execution time, that's no problem. But the results of the comparison of today (18th of August) and the first set date (1st of August) is wrong IMO. isAfter1 should be true and isBefore1 should be false; The comparison with the second set date (1st of October) is ok.

Any suggenstion what I'm doing wrong in the simple thing to compare two dates?

+3  A: 

In a Calendar object, month is 0-based, so August should be 7 and October should be 9.

Therefore, you just need to change your "sets" to have the correct numbers and it should work fine.

// 1st of August 2010
calFix.set( 2010, 7, 1 );

// 1st of October 2010
calFix.set( 2010, 9, 1 ); 
Kevin Crowell
Thanks, I didn't expect such an answer since I have a C# background and not Java. But starting the month at 0 surprises me. 0-based for the day of the week would be ok, but the month?!
infero
Why does it make any more or less sense for day of the week to be 0 based?
AHungerArtist
@infero I agree. It is counter-intuitive. It should either be all 0-base or all 1-based.
Kevin Crowell
@AHungerArtist because we also use numbers for day of the month and month of year and we all start at 1 in the real live. But for day of the week there are two "system": the Americans who start with Sunday and the Europeans who start with Monday as the first day of the week. So why making the world more complex as it already is?
infero