开发者

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.DateTimeFormatte开发者_开发技巧r;


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.


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)


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜