Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate a time span in Java and format the output?

I want to take two times (in seconds since epoch) and show the difference between the two in formats like:

  • 2 minutes
  • 1 hour, 15 minutes
  • 3 hours, 9 minutes
  • 1 minute ago
  • 1 hour, 2 minutes ago

How can I accomplish this??

like image 255
Jeremy Logan Avatar asked Mar 11 '09 19:03

Jeremy Logan


People also ask

Which data type is used for time in Java?

TIME Type. The time data type. The format is yyyy- MM -dd hh:mm:ss, with both the date and time parts maintained. Mapped to java.


1 Answers

Since everyone shouts "YOODAA!!!" but noone posts a concrete example, here's my contribution.

You could also do this with Joda-Time. Use Period to represent a period. To format the period in the desired human representation, use PeriodFormatter which you can build by PeriodFormatterBuilder.

Here's a kickoff example:

DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0); DateTime now = new DateTime(); Period period = new Period(myBirthDate, now);  PeriodFormatter formatter = new PeriodFormatterBuilder()     .appendYears().appendSuffix(" year, ", " years, ")     .appendMonths().appendSuffix(" month, ", " months, ")     .appendWeeks().appendSuffix(" week, ", " weeks, ")     .appendDays().appendSuffix(" day, ", " days, ")     .appendHours().appendSuffix(" hour, ", " hours, ")     .appendMinutes().appendSuffix(" minute, ", " minutes, ")     .appendSeconds().appendSuffix(" second", " seconds")     .printZeroNever()     .toFormatter();  String elapsed = formatter.print(period); System.out.println(elapsed + " ago"); 

Much more clear and concise, isn't it?

This prints by now

 32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago 

(Cough, old, cough)

like image 187
BalusC Avatar answered Sep 30 '22 00:09

BalusC