在Java中将秒数转换为HH:MM(无秒) [英] Convert number of seconds into HH:MM (without seconds) in Java

查看:118
本文介绍了在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(无秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆