views:

1884

answers:

4

Hi,

I find it funny that Java (or the java.util library) does not have a built-in function to calculate difference in dates. What is the best way to do this? I know the simple way is to take the difference of the time in milliseconds and then convert that into days. However, i wanted to know if this works in all cases (with daylight saving, etc.).

Thanks, Anirudh

+4  A: 

Java's not missing much, if you look at open source: try JODA.

duffymo
question about Java date ==> answer mentions Joda!
Steve McLeod
Yes, that's the way it works when a language has 2 defect date/time classes.
krosenvold
I looked at Joda - unfortunately, i am not allowed to use non-standard libraries :(
Anirudh
+1  A: 

I know the simple way is to take the difference of the time in milliseconds and then convert that into days. However, i wanted to know if this works in all cases (with daylight saving, etc.).

If your times are derived from UTC dates, or they are just the difference between two calls to System.getCurrentTimeMillis() measured on the same system, you will get a valid number of milliseconds as the difference, independent of any timezone issues. (which is why everything should be using UTC as a storage format -- it's much easier to go from UTC->local time; if you try to go the other way then you need to store the local timezone along with the local time -- or attempt to infer it, gack!)

As for turning this into a number of days, you should just be able to divide by 86400000... with the caveat that there is an occasional leap second every other year or so.

Jason S
A: 

Java's implementation of dates is poor. If you find JODA too complicated, try my little contribution to open source: http://calendardate.sourceforge.net/javadoc/index.html

+1  A: 

I disagree with the claim that Java doesn't have a mechanism for calculating the difference between dates.

Java was designed for global use. It was designed so that there isn't a concept of date, there is only a concept of "time in milliseconds". Any interpretation of such a universal time as the time-and-date in a specific location under a specific convention is merely a projection or a view.

The calendar class is used to turn this sort of absolute time into dates. You can also add or subtract date components, if you really need to. The only way to provide a difference in term of components between two times would be Calendar generated and specific. Thus, you could argue that the standard library does not include a smart enough Gregorian Calendar, and I would agree that it leaves some to be desired.

That being said, there are numerous implementations of this kind of functionality, I see others have provided examples.

Uri
I agree with you in principle. My claim of Java not having this functionality was based on the fact that other languages (Ruby, Python, etc) have a very simple (and working) implementation of adding and subtracting dates as part of the standard Date classes.
Anirudh