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

旧时模样 提交于 2019-12-24 04:07:08

问题


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.


回答1:


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)




回答2:


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


来源:https://stackoverflow.com/questions/5500171/how-to-use-joda-time-to-format-a-fixed-number-of-millisecons-to-hhmmss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!