Question

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?

Was it helpful?

Solution

Have you tried Joda Time?

OTHER TIPS

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

tl;dr

Duration.ofMillis( yourMillisecondsLongNumberGoesHere )
        .toDays()

Using java.time

The troublesome old date-time classes have been supplanted by the java.time classes.

I would like to display the number of days for a given long value of milliseconds

For a span of time involving hours, minutes, and seconds (and days defined as chunks of 24-hours), use the Duration class.

Duration d = Duration.ofMillis( yourMillisecondsLongNumberGoesHere );

To get the number of days, defined by defining the total number of whole seconds by 86,400L, call toDays.

long days = d.toDays();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top