• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calculating days between two dates  RSS feed

 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There must be any easy to do this that I can't see at the moment...
I'm trying to create a method that returns the number of days between 2 arbitrary dates, e.g. the there are 9 days between 1/10/2004 and 1/1/2004.
This is the simple code I started with:
(MILLIS_IN_DAY = 86400000L)

But this is flawed because of daylight savings time. For example:

Because 04/04/2004 was 1 hour short (spring forward), the output is "Diff = 0" instead of "Diff = 1".
So, any time there is a time change between the 2 dates that get passed into dateDiff(), the result will be incorrect.

Any idea how I can implement the dateDiff method and account for daylight savings?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple rounding would work:

This is analogous to adding 0.5 to the number before truncating it to an integer value. So both 23 and 25 hours round to 1 day.
 
Max Habibi
town drunk
( and author)
Sheriff
Posts: 4118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nice
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Max Habibi:
nice
I second that, thanks Jim.

Just to take things one step further... I didn't want the dateDiff method to return 0 in the following case:
dateX = 06/10/2004 00:00:00
dateY = 06/09/2004 23:00:00

So, I included a reducePrecision() method to take both dates down to only day precision. That way, the above dates become:
dateX = 06/10/2004 00:00:00
dateY = 06/09/2004 00:00:00
And the dateDiff method returns 1.

In case you're curious: Thanks again for the help!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!