我到处寻找将秒转换为 hh:mm:ss 但找不到合适的
我创建了一个程序,允许用户输入两个不同的时间,然后计算差值
将输入的时间拆分为 hh * 3600 - mm * 60 - ss,然后转换为秒并相互相减以计算秒差
例如 12:12:12 和 13:13:13 会给我 3661 秒,但我不知道如何将差异转换回 hh:mm:ss
任何帮助将不胜感激
最佳答案
使用旧的java date api(不推荐,见评论):
int sec = .... //
Date d = new Date(sec * 1000L);
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); // HH for 0-23
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String time = df.format(d);
另见 SimpleDateFormat
.
注意:根据评论,如果秒数超过一天中的秒数 (86400),则无法按预期工作。在这种情况下,必须采取不同的方法。
编辑:如果您正在使用 JDK 8你可以这样写:
int sec = ...
Duration duration = Duration.ofSeconds(sec);
这个持续时间对象更好地代表了你在说什么。我正在尝试找出如何按照您的意愿对其进行格式化,但到目前为止我没有运气。
编辑 2:在 JDK 8 之前,您可以使用 Joda API :
int sec = ...
Period period = new Period(sec * 1000L);
String time = PeriodFormat.getDefault().print(period); // you can customize the format if this one doesn't cut it
这可能是最优雅的解决方案。另见 this .
编辑 3:根据评论,我明确添加了时区。
关于java - 如何将秒数转换为 hhmmss,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22545644/