Maxim Veksler
Maxim Veksler

Reputation: 30182

How to use joda time to format a fixed number of millisecons to hh:mm:ss?

I have input, 34600 milliseconds I would like to output this in the format 00:00:34 (HH:MM:SS).

What classes should I look at JDK / Joda-time for this? I need this to be efficient, preferably thread safe to avoid object creations on each parsing.

Thank you.

-- EDIT --

Using this code produces time zone sensitive results, how can I make sure the formating is "natural", i.e. uses absolute values.

import java.util.Locale;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


public class Test {
    public static void main(String[] args) {
        DateTimeFormatter fmt = DateTimeFormat.forPattern("kk:mm:ss").withLocale(new Locale("UTC"));
        System.out.println(fmt.print(34600));
    }
}

Results in 02:00:34 - The +2h is because my time zone is GMT+2. While the expected output is 00:00:34.

Upvotes: 2

Views: 3515

Answers (2)

Rob Hruska
Rob Hruska

Reputation: 120286

For a Joda solution, give this a try (given your updated question):

PeriodFormatter fmt = new PeriodFormatterBuilder()
        .printZeroAlways()
        .minimumPrintedDigits(2)
        .appendHours()
        .appendSeparator(":")
        .printZeroAlways()
        .minimumPrintedDigits(2)
        .appendMinutes()
        .appendSeparator(":")
        .printZeroAlways()
        .minimumPrintedDigits(2)
        .appendSeconds()
        .toFormatter();
Period period = new Period(34600);
System.out.println(fmt.print(period));

Outputs:

00:00:34

Regarding your preference for thread safety:

PeriodFormatterBuilder itself is mutable and not thread-safe, but the formatters that it builds are thread-safe and immutable.

(from PeriodFormatterBuilder documentation)

Upvotes: 11

Peter Lawrey
Peter Lawrey

Reputation: 533530

You could use String.format?

long millis = 34600;
long hours = millis/3600000;
long mins = millis/60000 % 60;
long second = millis / 1000 % 60;
String time = String.format("%02d:%02d:%02d", hours, mins, secs);

Upvotes: 3

Related Questions