Monday, May 24, 2010

How do I determine the number of days between two times in Java?

So, given two dates that could be days, weeks, months, or even years apart, is there an easy way to determine the number of days between them?

How do I determine the number of days between two times in Java?
If you have two instances of 'Calendar', you can call their getTimeInMillis() and perform the math on that. If you have Date objects, math on getTime() would work just as well.





The difference, divided by 86400000, would be the difference in days.
Reply:This is actually not a very easy problem to solve using your own calculations because the values can get thrown by Daylight Savings Times. Use the Java Date/Calendar classes instead.





Do NOT just take the timestamps and divide by number of ms/day. This is not always correct.





Here is a link to an article with more details:





http://www.xmission.com/~goodhill/dates/...


No comments:

Post a Comment