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

查看:36
本文介绍了如何在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 时间PeriodFormatter.如果你真的有一个持续时间(即经过的时间,没有参考日历系统)那么你可能应该在大多数情况下使用 Duration - 然后你可以调用 toPeriod(指定您想要反映 25 小时是否变为 1 天和 1 小时等的任何 PeriodType)以获取您可以格式化的 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 或更高版本:我通常建议使用 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;
}

以这种方式格式化相当简单,如果手动操作很烦人.对于解析来说,这通常变得更难了……当然,如果您愿意,即使使用 Java 8,您仍然可以使用 Joda Time.

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天全站免登陆