• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Calculating days between two dates

 
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
nice
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
reply
    Bookmark Topic Watch Topic
  • New Topic