views:

950

answers:

4

I'm familiar with the the date and time classes in the JDK and their associated formatting methods. I may be blind, but I cannot find an equivalent set of classes for processing time intervals. For example, I would like to display the number of days for a given long value of milliseconds. I realize that the method to do these conversions is quite simple, however when you factor in internationalization and localization support this becomes less trivial.

I'm surprised that the JDK is missing support for interval processing. However, databases such as Postgresql support it.

Basically what I'm looking for in the JDK (if I'm too blind to see it) or in a third party library is the following functionality:

  • Time calculation methods. Such as milliseconds to weeks or seconds to nanoseconds. Although the math is simple for these operations, having an API to go through seems more self-documenting to me.
  • Time interval formatting functions that format according to the passed Locale like DateFormat works. For example, in EN_US I would assume that 10 days is well "10 days" and in Japanese I would want "10日" returned.

Is there anything out there or is this a canidate for a new open-source project?

+3  A: 

have a look at http://commons.apache.org/ and the DateUtils class there

Tobiask
In what project is that class?
Elijah
+1 Got it. It is in the lang package. Nice to know it is there since I'm already importing lang in my current project.
Elijah
+9  A: 

Have you tried Joda Time?

jassuncao
+1 Joda Time looks pretty awesome. It has interval processing in addition to good localized calendar support.
Elijah
This is becoming almost a cliché. (See the comments on http://stackoverflow.com/questions/635935/how-can-i-calculate-a-time-span-in-java-and-format-the-output and http://stackoverflow.com/questions/643402/simple-java-date-calculations, and probably every question in the "related" section.)
Michael Myers
Maybe this should tell the java developers something about an obvious omission in the jdk. Hey - you guys listening?
Elijah
Everybody knows the date time classes provided by the JDK lack a lot of features. Sun recognizes this. I think the developer of Joda Time is now working for sun. Hopefully, the next version of Java will have an improved time api.
jassuncao
A: 

Unfortunately there is nothing like this in the Standard Library, but as Tobiask points out the Apache Commons have a useful tool for this.

DurationFormatUtils has a few predefined formats (Hour:Minutes:Second, ISO) and allows you to specify your own.

Kris