如何将秒转换以这种格式" HH:MM:SS" [英] How to convert the seconds in this format "HH:mm:ss"
问题描述
欲第二/毫秒转换这种格式HH:MM:SS(用于esamples,从5秒到0点○○分05秒)。我试图让这样的格式:
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:
int millis = 5000;
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
String time = df.format(millis);
在这种方式,我得到1点00分05秒,而不是00:00:05。我在哪里错了?
In that way, I get "01:00:05" and not "00:00:05". Where am I wrong?
推荐答案
时区。
长值 5000
指时代后5秒。对于大多数时区,时代在5秒钟之内没有5秒过去当地时间的午夜。
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.
8的Java更新
java.time.LocalTime
将处理墙上时钟一天中的时间的想法而不必担心时区和天隐含在 java.util.Date
。如果您可以使用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:
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();
(我猜严格来说, java.time.Duration
是一个更好的模式的你想要的东西,因为它重新presents若干秒,而不是时间,一天的,但它是一个痛苦的格式化为HH:MM:SS,所以如果你总是处理子24小时值的TimeOfDay给你这个格式的自由和在其他等价的。)
(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 7或以下,则显式指定在你的榜样code GMT
的时区应该给你你所期望的输出。
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.
下面是一个斯卡拉REPL会话演示问题,以及Java 7的解决方案,我的机器上:
Here's a Scala REPL session demonstrating the problem, and Java 7 solution, on my machine:
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
所以,你可以看到,我的默认时区是 GB
,其中有1小时,从格林尼治时间记为时间5000L 偏移code>。设置时区为GMT gievs的期望输出
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
.
这篇关于如何将秒转换以这种格式" HH:MM:SS"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!