views:

45

answers:

1

I am trying to compare dates and I have found where my code goes wrong, but I don't know why.

I am trying to compare a date with todays date (using Gregorian Calendars only). I have printed out todays date where ever it is mentioned in the code and in one place it magically changes from year 2010 to year 3910 (todays year + 1900).

Does anyone know any reason for this? I will post my code if needed but I honestly haven't changed the date object at all.

As requested here's the code:

    //Prints out 2010   
    System.out.println("TodaysDate.getYear():\t" + todaysDate.getYear());
    //Prints out 2010
    System.out.println(todaysDate); 

    //Getting a year from a string (it is 2010)
    todaysDate.setYear(Integer.parseInt(yea));

    //Prints out 2010   
    System.out.println("TodaysDate.getYear():\t" + todaysDate.getYear());
    //Prints out 3910   
    System.out.println(todaysDate);
+2  A: 

The date is typically stored as "number of years since 1900", so you need to compensate for that. You can see that in the documentation for Date: http://developer.android.com/reference/java/util/Date.html

EDIT: I should mention what I posted as a comment. Jeff Sharkey recommended against the Calendar class (if you're using that too). android.text.format.DateUtils is much more lightweight (you'll see that the phone stalls for a little bit when you first load the Calendar class, especially on old phones). DateUtils is available in Android 1.5 and up.

EboMike
Was just about to post the same thing. The javadoc for setYear shows that it adds 1900 to the value you pass in. It also shows that setYear is deprecated and to use Calendar.set(Calendar.YEAR, year + 1900) instead. But it looks like you could just use Calendar.set(Calendar.YEAR, year), which would work with your code above because your year value is not offset by 1900.
Marc Bernstein
Hmmm. That is strange. Thank yous. But why would "todaysDate.getYear()" print out 2010 everytime?
TehGoose
The Calendar class is extremely heavy-handed though. Jeff Sharkey recommended against using it - starting with Android 1.5, android.text.format.DateUtils was introduced as a much more lightweight alternative.
EboMike
@Teh: Because getYear() also returns the number of years since 1900, so if the actual year it is trying to represent is 3910, then getYear() returns 2010.
EboMike
Thanks guys. I should be able to continue now :)
TehGoose