Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to Calculate and format time/date intervals in java?

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?

like image 261
Elijah Avatar asked Mar 18 '09 11:03

Elijah


People also ask

How do you calculate duration in Java?

Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates.

Can you format calendar in Java?

The DateFormat class in Java is used for formatting dates. A specified date can be formatted into the Data/Time string. For example, a date can be formatted into: mm/dd/yyyy.

Which string method is used to calculate date and time?

String dateStart = "11/03/14 09:29:58"; String dateStop = "11/03/14 09:33:43"; // Custom date format SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.

How do I format a date in Java 8?

Java 8 provides APIs for the easy formatting of Date and Time: LocalDateTime localDateTime = LocalDateTime. of(2015, Month. JANUARY, 25, 6, 30);


2 Answers

Have you tried Joda Time?

like image 50
jassuncao Avatar answered Sep 20 '22 11:09

jassuncao


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

like image 25
Tobias Avatar answered Sep 21 '22 11:09

Tobias