如何格式化java中的持续时间? (例如格式H:MM:SS) [英] How to format a duration in java? (e.g format H:MM:SS)

查看:110
本文介绍了如何格式化java中的持续时间? (例如格式H:MM:SS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用像H:MM:SS这样的模式格式化持续时间(以秒为单位)。 java中的当前实用程序旨在格式化时间而不是持续时间。

I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.

推荐答案

如果您使用的是Java版本在8之前...你可以使用 Joda Time PeriodFormatter 。如果你真的有一个持续时间(即没有参考日历系统的时间,那么你应该在大多数情况下使用持续时间 - 你然后可以调用 toPeriod (指定任何 PeriodType 你要反映25小时是否为1天1小时,等)获得 Period 你可以格式化。

If you're using a version of Java prior to 8... you can use Joda Time and PeriodFormatter. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using Duration for the most part - you can then call toPeriod (specifying whatever PeriodType you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a Period which you can format.

如果您使用的是Java 8或更高版本:I通常建议使用 java.time.Duration 来表示持续时间。然后,您可以调用 getSeconds()等来获取标准字符串格式的整数,如果需要,可以根据bobince的答案获取 - 尽管您应该注意以下情况:持续时间为负,因为您可能希望输出字符串中有单个负号。所以类似于:

If you're using Java 8 or later: I'd normally suggest using java.time.Duration to represent the duration. You can then call getSeconds() or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a single negative sign in the output string. So something like:

public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    long absSeconds = Math.abs(seconds);
    String positive = String.format(
        "%d:%02d:%02d",
        absSeconds / 3600,
        (absSeconds % 3600) / 60,
        absSeconds % 60);
    return seconds < 0 ? "-" + positive : positive;
}

格式化这种方式合理简单,如果烦人的话手册。对于解析一般来说它变得更难了......当然,如果你愿意的话,你仍然可以使用Joda Time甚至Java 8.

Formatting this way is reasonably simple, if annoyingly manual. For parsing it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.

这篇关于如何格式化java中的持续时间? (例如格式H:MM:SS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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