programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• Tim Cooke
• Junilu Lacar
Sheriffs:
• Rob Spoor
• Devaka Cooray
• Jeanne Boyarsky
Saloon Keepers:
• Jesse Silverman
• Stephan van Hulst
• Tim Moores
• Carey Brown
• Tim Holloway
Bartenders:
• Jj Roberts
• Al Hobbs
• Piet Souris

# Calculating days between two dates

Ranch Hand
Posts: 331
• Number of slices to send:
Optional 'thank-you' note:
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?

Wanderer
Posts: 18671
• Number of slices to send:
Optional 'thank-you' note:
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.

town drunk
( and author)
Posts: 4118
• Number of slices to send:
Optional 'thank-you' note:
nice

Blake Minghelli
Ranch Hand
Posts: 331
• Number of slices to send:
Optional 'thank-you' note:

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!

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?