• Post Reply Bookmark Topic Watch Topic
  • New Topic

getTime() logic giving variable date  RSS feed

 
sharad shailly
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm using following code :

1.

2. We then pass the above 'lastPaymentDate' to following method



After this we only compare the above two dates - sTBALowDate.getTime() and compareDate.getTime(). But at runtime they don't evaluate to be equal. I'm not sure why.

I'm simply hard coding year, day, month in the calendar instance but when I use getTime() method on the dates, the day gets incremented by 1 for 'compareDate' , whereas for 'sTBALowDate' it doesn't get incremented.

My requirement is to compare above two dates and evaluate whether they are equal or not (here I'm hardcoding all values for both dates). Should I not be using getTime() method. Is there a simpler way to compare dates here?

PS : Looks like getTime() has to do with the timezone value. But while debugging code, I have found getTime() giving me different 'day' value - sometimes it increments by 1 and other times it doesn't. Quite strange.
 
Paul Clapham
Sheriff
Posts: 22834
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of your "set time part to zero" methods sets the time in your time zone to zero. The other sets the time in GMT to zero. If your time zone isn't GMT then yes, they are not equal.

It seems like you already suspected time zone issues, so probably your next step would have been to ask "Just why are we setting the time part to zero in two different ways anyway?" So I'm asking that.

The best thing to do, if you're using Java 8, is to get rid of the Calendar class and start using LocalDate objects (from the java.time package) when you want to work with dates and you don't want time zones to mess you up. If you aren't using Java 8 then you could use similar classes from the JodaTime package.

Or you could just use the code from lines 13-17 of isEqualToLowDate in all cases where you want to set the time part to zero.

 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!