如何以这种格式转换秒数“HH:mm:ss”

时间:2021-12-19 02:44:44

I want to convert the second/milliseconds in this format "HH:mm:ss" (for esamples, from 5 seconds to 00:00:05). I tried to get that format in this way:

我想以这种格式转换第二个/毫秒“HH:mm:ss”(对于例子,从5秒到00:00:05)。我试图以这种方式获得这种格式:

int millis = 5000;
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
String time = df.format(millis);

In that way, I get "01:00:05" and not "00:00:05". Where am I wrong?

这样,我得到“01:00:05”而不是“00:00:05”。我哪里错了?

6 个解决方案

#1


19  

Timezones.

The long value 5000 means 5 seconds after the epoch. For the majority of timezones, 5 seconds after the epoch is not 5 seconds past midnight local time.

长值5000意味着在纪元后5秒。对于大多数时区,在纪元后5秒不是当地时间午夜过后5秒。

Java 8 update:

Java 8更新:

java.time.LocalTime will handle the idea of a wall-clock "time of day" without you having to worry about the timezones and days implicit in java.util.Date. If you can use Java 8, and your durations will always be less than a day, then a correct version of your example can be as simple as:

java.time.LocalTime将处理挂钟“时间”的想法,而不必担心java.util.Date中隐含的时区和天数。如果您可以使用Java 8,并且您的持续时间总是少于一天,那么您的示例的正确版本可以如下所示:

int millis = 5000;
int seconds = millis / 1000; // Maybe no need to divide if the input is in seconds
LocalTime timeOfDay = LocalTime.ofSecondOfDay(seconds);
String time = timeOfDay.toString();

(I guess strictly speaking, java.time.Duration is a better model of what you want, in that it represents a certain number of seconds, rather than a time-of-day. But it's a pain to format into hh:mm:ss, so if you're always dealing with sub-24hour values, TimeOfDay gives you this formatting for free and is otherwise equivalent.)

(我想严格来说,java.time.Duration是你想要的更好的模型,因为它代表了一定的秒数,而不是一天中的时间。但是格式化为hh:mm很痛苦: ss,所以如果你总是在处理24小时以下的值,TimeOfDay会免费为你提供这种格式,在其他方面是等价的。)


If you're stuck with Java 7 or below, then explicitly specifying a timezone of GMT in your example code should give you the output you expect.

如果您坚持使用Java 7或更低版​​本,那么在示例代码中明确指定GMT的时区应该会为您提供所期望的输出。

Here's a Scala REPL session demonstrating the problem, and Java 7 solution, on my machine:

这是一个Scala REPL会话,在我的机器上演示了问题和Java 7解决方案:

scala> val millis = 5000
millis: Int = 5000

scala> val df = new java.text.SimpleDateFormat("HH:mm:ss")
df: java.text.SimpleDateFormat = java.text.SimpleDateFormat@8140d380

scala> df.format(millis)
res0: java.lang.String = 01:00:05

scala> df.getTimeZone.getID
res1: java.lang.String = GB

scala> df.getTimeZone.getOffset(millis)
res2: Int = 3600000

scala> df.setTimeZone(java.util.TimeZone.getTimeZone("GMT"))

scala> df.format(millis)
res3: java.lang.String = 00:00:05

So you can see that my default time zone is GB, which has a 1 hour offset from GMT at the time denoted by 5000L. Setting the timezone to GMT gievs the expected output of 00:00:05.

所以你可以看到我的默认时区是GB,它与GMT在5000L表示的时间有1小时的偏移。将时区设置为GMT gievs 00:00:05的预期输出。

#2


12  

I got this to work. Let me know if it works for you. Seems like a lot of lines to do something seemingly simple..

我得到了这个工作。请让我知道这对你有没有用。似乎很多线路做一些看似简单的事情..

    int millis = 5000;
    TimeZone tz = TimeZone.getTimeZone("UTC");
    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(tz);
    String time = df.format(new Date(millis));
    System.out.println(time);

#3


5  

You should get SimpleDateFormat with Locale argument.

您应该使用Locale参数获取SimpleDateFormat。

public static String getDateFromMillis(long millis) {
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    return formatter.format(new Date(millis));
}

#4


3  

I wrote a simple utility function for this task which does not require any Java version nor instantiates any unnecessary objects:

我为此任务编写了一个简单的实用程序函数,它不需要任何Java版本,也不实例化任何不必要的对象:

/**
 * provides a String representation of the given time
 * @return {@code millis} in hh:mm:ss format
 */
public static final String formatTime(long millis) {
    long secs = millis / 1000;
    return String.format("%02d:%02d:%02d", secs / 3600, (secs % 3600) / 60, secs % 60);
}

Unlike some other solutions here, this can even deal with up to 100 hours

与此处的其他解决方案不同,这甚至可以处理长达100小时

#5


1  

public class HHMMSS {

        final int UUR = 3600;
        final int MINUUT = 60;

    public void converteerTijd() {

        int uren, minuten, seconden, ingave;
        System.out.print("Geef een aantal seconden: ");
        ingave = Input.readInt();
        uren = ingave / UUR;
        minuten = (ingave - uren * UUR) / MINUUT;
        seconden = ingave - uren * UUR - minuten * MINUUT;
        String nU1 = (uren < 10) ? "0" : "";
        String nM1 = (minuten < 10) ? "0" : "";
        String nS1 = (seconden < 10) ? "0" : "";
        System.out.println(nU1 + uren + "-" + nM1 + minuten + "-" + nS1 + seconden);

#6


1  

Java 9 answer:

Java 9回答:

    Duration dur = Duration.ofMillis(millis);
    System.out.println(String.format("%02d:%02d:%02d",
                       dur.toHours(), dur.toMinutesPart(), dur.toSecondsPart()));

(not tested yet)

(尚未测试)

The toXxPart methods are described in the API docs for Java 9.

toxxPart方法在Java 9的API文档中描述。

#1


19  

Timezones.

The long value 5000 means 5 seconds after the epoch. For the majority of timezones, 5 seconds after the epoch is not 5 seconds past midnight local time.

长值5000意味着在纪元后5秒。对于大多数时区,在纪元后5秒不是当地时间午夜过后5秒。

Java 8 update:

Java 8更新:

java.time.LocalTime will handle the idea of a wall-clock "time of day" without you having to worry about the timezones and days implicit in java.util.Date. If you can use Java 8, and your durations will always be less than a day, then a correct version of your example can be as simple as:

java.time.LocalTime将处理挂钟“时间”的想法,而不必担心java.util.Date中隐含的时区和天数。如果您可以使用Java 8,并且您的持续时间总是少于一天,那么您的示例的正确版本可以如下所示:

int millis = 5000;
int seconds = millis / 1000; // Maybe no need to divide if the input is in seconds
LocalTime timeOfDay = LocalTime.ofSecondOfDay(seconds);
String time = timeOfDay.toString();

(I guess strictly speaking, java.time.Duration is a better model of what you want, in that it represents a certain number of seconds, rather than a time-of-day. But it's a pain to format into hh:mm:ss, so if you're always dealing with sub-24hour values, TimeOfDay gives you this formatting for free and is otherwise equivalent.)

(我想严格来说,java.time.Duration是你想要的更好的模型,因为它代表了一定的秒数,而不是一天中的时间。但是格式化为hh:mm很痛苦: ss,所以如果你总是在处理24小时以下的值,TimeOfDay会免费为你提供这种格式,在其他方面是等价的。)


If you're stuck with Java 7 or below, then explicitly specifying a timezone of GMT in your example code should give you the output you expect.

如果您坚持使用Java 7或更低版​​本,那么在示例代码中明确指定GMT的时区应该会为您提供所期望的输出。

Here's a Scala REPL session demonstrating the problem, and Java 7 solution, on my machine:

这是一个Scala REPL会话,在我的机器上演示了问题和Java 7解决方案:

scala> val millis = 5000
millis: Int = 5000

scala> val df = new java.text.SimpleDateFormat("HH:mm:ss")
df: java.text.SimpleDateFormat = java.text.SimpleDateFormat@8140d380

scala> df.format(millis)
res0: java.lang.String = 01:00:05

scala> df.getTimeZone.getID
res1: java.lang.String = GB

scala> df.getTimeZone.getOffset(millis)
res2: Int = 3600000

scala> df.setTimeZone(java.util.TimeZone.getTimeZone("GMT"))

scala> df.format(millis)
res3: java.lang.String = 00:00:05

So you can see that my default time zone is GB, which has a 1 hour offset from GMT at the time denoted by 5000L. Setting the timezone to GMT gievs the expected output of 00:00:05.

所以你可以看到我的默认时区是GB,它与GMT在5000L表示的时间有1小时的偏移。将时区设置为GMT gievs 00:00:05的预期输出。

#2


12  

I got this to work. Let me know if it works for you. Seems like a lot of lines to do something seemingly simple..

我得到了这个工作。请让我知道这对你有没有用。似乎很多线路做一些看似简单的事情..

    int millis = 5000;
    TimeZone tz = TimeZone.getTimeZone("UTC");
    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(tz);
    String time = df.format(new Date(millis));
    System.out.println(time);

#3


5  

You should get SimpleDateFormat with Locale argument.

您应该使用Locale参数获取SimpleDateFormat。

public static String getDateFromMillis(long millis) {
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    return formatter.format(new Date(millis));
}

#4


3  

I wrote a simple utility function for this task which does not require any Java version nor instantiates any unnecessary objects:

我为此任务编写了一个简单的实用程序函数,它不需要任何Java版本,也不实例化任何不必要的对象:

/**
 * provides a String representation of the given time
 * @return {@code millis} in hh:mm:ss format
 */
public static final String formatTime(long millis) {
    long secs = millis / 1000;
    return String.format("%02d:%02d:%02d", secs / 3600, (secs % 3600) / 60, secs % 60);
}

Unlike some other solutions here, this can even deal with up to 100 hours

与此处的其他解决方案不同,这甚至可以处理长达100小时

#5


1  

public class HHMMSS {

        final int UUR = 3600;
        final int MINUUT = 60;

    public void converteerTijd() {

        int uren, minuten, seconden, ingave;
        System.out.print("Geef een aantal seconden: ");
        ingave = Input.readInt();
        uren = ingave / UUR;
        minuten = (ingave - uren * UUR) / MINUUT;
        seconden = ingave - uren * UUR - minuten * MINUUT;
        String nU1 = (uren < 10) ? "0" : "";
        String nM1 = (minuten < 10) ? "0" : "";
        String nS1 = (seconden < 10) ? "0" : "";
        System.out.println(nU1 + uren + "-" + nM1 + minuten + "-" + nS1 + seconden);

#6


1  

Java 9 answer:

Java 9回答:

    Duration dur = Duration.ofMillis(millis);
    System.out.println(String.format("%02d:%02d:%02d",
                       dur.toHours(), dur.toMinutesPart(), dur.toSecondsPart()));

(not tested yet)

(尚未测试)

The toXxPart methods are described in the API docs for Java 9.

toxxPart方法在Java 9的API文档中描述。