Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert joda-time seconds to formatted time string

Tags:

java

jodatime

say I have 110 seconds that I want to convert to 01:50 or 00:01:50 or such. How do I do that in joda-time? I load the number into Seconds but then toString is not doing the conversion for me.

like image 498
learner Avatar asked Mar 15 '14 06:03

learner


People also ask

How to convert a time in seconds to a string format?

Given a time in seconds and the task is to convert the time into a string format hh:mm:ss. There are two approaches to solve this problem: The Date () constructor expects a UNIX timestamp as one of its forms. A UNIX timestamp is a number of milliseconds that have passed since the epoch time (January 1, 1970, 00:00:00 UTC).

How to download the Joda Time file?

To download the Joda Time .jar file you can visit Joda Time releases page at github.com/JodaOrg/joda-time DateTimeToStringISO.java

How do I convert a date to a string in Java?

The seconds value is extracted from the date using the getSeconds () method. The final formatted date is created by converting each of these values to a string using the toString () method and then padding them with an extra ‘0’, if the value is a single-digit by using the padStart () method.

Does Joda Time treat a 4 digit year as 2 digit?

I am trying to use JODA time to set format (MMddyyyy hh:mm a) , but it turns out it treats a 4 digit year as 2 digit. I get an error while parsing, IllegalArgumentExceptionas 2013/9/8 formed as 13/9/8.


1 Answers

LocalTime time = new LocalTime(0, 0); // midnight
time = time.plusSeconds(110);
String output = DateTimeFormat.forPattern("HH:mm:ss").print(time);
System.out.println(output); // 00:01:50

Note this answer is valid for amounts of seconds less than one full day (86400). If you have bigger numbers then better use a formatter for durations (in Joda-Time called PeriodFormatter) - see also the right answer of @Isaksson.

like image 144
Meno Hochschild Avatar answered Sep 24 '22 23:09

Meno Hochschild