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

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

我知道您可以使用 DateUtils.formatElapsedTime(seconds) 将秒数转换为 HH:MM 格式的 String:SS.但是是否有任何实用函数可以让我执行相同的转换但没有秒?

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?

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

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.

推荐答案

根据可用信息,您似乎想要格式化基于持续时间的值.幸运的是,从 Java 8 开始,现在有一个新的 java.time API,其中包含一个 Duration 类.

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

打印出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:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497517.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不含   转换为   中将   Java   HH

发布评论

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

>www.elefans.com

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