在Java中将秒数转换为HH:MM(无秒)

编程入门 行业动态 更新时间:2024-10-24 06:28:00
本文介绍了在Java中将秒数转换为HH:MM(无秒)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道您可以使用 DateUtils.formatElapsedTime(秒)将秒数转换为字符串格式为 HH:MM:SS 。但有没有任何实用功能可以让我执行相同的转换,但没有秒?

例如,我想要转换 3665 秒进入 1:01 ,即使它正好是 1:01:05 。换句话说,只需删除秒部分。

强烈会更喜欢指向效用函数(如果存在)的答案而不是一堆家庭滚动算法。

解决方案

根据可用信息,您似乎想要格式化基于持续时间的值。幸运的是,自Java 8以来,现在有了一个新的 java.time API,其中包含持续时间类。 / p>

不幸的是,它没有(至少在最后一次检查时)支持格式化程序。

但是,你可以轻松自己滚动......

protected static字符串格式(持续时间){长时间= duration.toHours(); long mins = duration.minusHours(hours).toMinutes(); 返回String.format(%02d:%02d,小时,分钟); }

与...类似的东西使用...

System.out.println(format(Duration.ofSeconds(3665)));

打印出 01:01 。

现在我知道你更喜欢实用工具方法,但是你不太可能找到适合你每个需求的东西,而且至少给你一个起点。此外,你总是可以提出拉动请求;)

I'm aware that you can use DateUtils.formatElapsedTime(seconds) to convert a number of seconds into a String with the format HH:MM:SS. But are there any utility functions that let me perform the same conversion but without the seconds?

For example, I want to convert 3665 seconds into 1:01, even though it's exactly 1:01:05. In other words, simply dropping the seconds part.

Would strongly prefer an answer that points to a utility function (if one exists) rather than a bunch of home rolled algorithms.

解决方案

Based on the available information, you seem to be wanting to format a duration based value. Lucky for us, since Java 8, there is now a new java.time API which includes a Duration class.

Unfortunately, it doesn't (at least the last time checked) support a formatter for it.

However, you could easily roll your own...

protected static String format(Duration duration) { long hours = duration.toHours(); long mins = duration.minusHours(hours).toMinutes(); return String.format("%02d:%02d", hours, mins); }

Which when used with something like...

System.out.println(format(Duration.ofSeconds(3665)));

prints out 01:01.

Now I know you'd "prefer" utility methods, but you're unlikely to find something that fits your "every" need and this at least gives you a starting point. Besides, you could always make a pull request ;)

更多推荐

在Java中将秒数转换为HH:MM(无秒)

本文发布于:2023-10-16 12:12:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497518.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   Java   HH   MM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!