在 Java 8 / jsr310 中格式化持续时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20827047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:38:23  来源:igfitidea点击:

Formatting a Duration in Java 8 / jsr310

javajava-8jodatimedurationjava-time

提问by Chad Lowe

I am transitioning a project from Joda-Time to java8's native time libraries, and I have run into a snag.

我正在将一个项目从 Joda-Time 转换为 java8 的本机时间库,但遇到了障碍。

I have been unable to find a formatter for Duration. I would like to have a custom String format of, for instance, HHH+MM, where a Duration of 75 hours and 15 minutes would format as "75+15".

我一直无法找到 Duration 的格式化程序。我想要一个自定义的 String 格式,例如,HHH+MM,其中 75 小时 15 分钟的 Duration 格式为"75+15"

This was easy to do with Joda-Time by converting to period, and using a PeriodFormatter, but I have been unable to find this type of class in Java8. Am I missing something?

通过转换为句点并使用 PeriodFormatter,使用 Joda-Time 很容易做到这一点,但是我一直无法在 Java8 中找到这种类型的类。我错过了什么吗?

采纳答案by Meno Hochschild

There is no period/duration-formatter in jsr-310, different from JodaTime. Not every feature of JodaTime was ported to JSR-310 (for example also not PeriodType). And in reverse JSR-310 has some features which are not available in JodaTime (for example localized weekday numbers or the strategy pattern approach with adjusters).

jsr-310 中没有 period/duration-formatter,与 JodaTime 不同。并非 JodaTime 的每个功能都被移植到 JSR-310(例如也不是 PeriodType)。相反,JSR-310 有一些在 JodaTime 中不可用的功能(例如本地化的工作日数字或带有调整器的策略模式方法)。

It might happen that Java 9 will introduce some kind of built-in period formatting (read something about this from S. Colebourne).

Java 9 可能会引入某种内置的句点格式(从 S. Colebourne 阅读有关此内容的一些内容)。

Conclusion: JSR-310 and JodaTime are not fully compatible to each other, so a lot of work can be required. I would not be so keen on migration as soon as possible. Do you need special features of JSR-310 which are not offered by JodaTime?

结论:JSR-310 和 JodaTime 并不完全兼容,因此可能需要做很多工作。我不会那么热衷于尽快移民。您是否需要 JodaTime 不提供的 JSR-310 的特殊功能?

Additional note: You should also be aware of the fact that joda period (which includes all units from years to seconds) is not fully compatible with jsr310-period (only years, months, days) or jsr310-duration (only hours, minutes, seconds and fraction seconds).

附加说明:您还应该意识到 joda period(包括从年到秒的所有单位)与 jsr310-period(仅年、月、日)或 jsr310-duration(仅小时、分钟、秒和小数秒)。

回答by assylias

There is no built-in method but you can access the number of hours/minutes without having to calculate them manually. Your specific format could look like:

没有内置方法,但您可以访问小时/分钟数,而无需手动计算它们。您的特定格式可能如下所示:

Duration d = Duration.of(75, HOURS).plusMinutes(15);
long hours = d.toHours(); //75
long minutes = d.minusHours(hours).toMinutes(); //15
String HH_PLUS_MM = hours + "+" + minutes; //75+15
System.out.println(HH_PLUS_MM);

If the duration is guaranteed to be less than 24 hours, you can also use this trick:

如果保证持续时间小于24小时,你也可以使用这个技巧:

String hhPlusMm = LocalTime.MIDNIGHT.plus(d).format(DateTimeFormatter.ofPattern("HH+mm"));

回答by CodeBlind

I know this is an old question but I recently ran into the same thing. There really shouldbe a better solution than this, but this worked for me:

我知道这是一个老问题,但我最近遇到了同样的问题。确实应该有比这更好的解决方案,但这对我有用:

public static String millisToElapsedTime(long millis){
    DateFormat fmt = new SimpleDateFormat(":mm:ss.SSS");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    return (millis/3600000/*hours*/)+fmt.format(new Date(millis));
}

Then, you could add this:

然后,您可以添加以下内容:

public static String durationToElapsedTime(Duration d){
    return millisToElapsedTime(d.toMillis());
}

回答by Basil Bourque

Java 9 and later: Duration::to…Partmethods

Java 9 及更高版本:Duration::to…Part方法

In Java 9 the Durationclass gained new to…Partmethodsfor returning the various parts of days, hours, minutes, seconds, milliseconds/nanoseconds. See this pre-release OpenJDK source code.

在 Java 9 中,Duration该类获得to…Part了返回天、小时、分钟、秒、毫秒/纳秒的各个部分的方法。请参阅此预发布 OpenJDK 源代码

Given a duration of 49H30M20.123S…

鉴于持续时间为 49H30M20.123S…

  • toNanosPart()= 123000000
  • toMillisPart()= 123
  • toSecondsPart()= 20
  • toMinutesPart()= 30
  • toHoursPart()= 1
  • toDaysPart()= 2
  • toNanosPart()= 123000000
  • toMillisPart()= 123
  • toSecondsPart()= 20
  • toMinutesPart()= 30
  • toHoursPart()= 1
  • toDaysPart()= 2

Remember that “days” here means chunks of 24-hours, ignoring dates on a calendar. If you care about dates, use Periodclass instead.

请记住,这里的“天”是指 24 小时的块,忽略日历上的日期。如果您关心日期,请改用Periodclass。

I do not know if any additional formatter features are added. But at least you will be able to more conveniently generate your own strings from numbers obtained via these new getter methods.

我不知道是否添加了任何其他格式化程序功能。但至少您将能够更方便地从通过这些新的 getter 方法获得的数字生成您自己的字符串。

Java 8

爪哇 8

Oddly enough, no convenient getter methods for these values were included in the first edition release of java.time in Java 8. One of very few oversights in the otherwise excellent design of the java.timeframework.

奇怪的是,Java 8 中的 java.time 的第一版中没有包含用于这些值的方便的 getter 方法。在java.time框架的其他优秀设计中,这是极少数疏忽之一。

See the related Question: Why can't I get a duration in minutes or hours in java.time?.

请参阅相关问题:为什么我无法在 java.time 中获得以分钟或小时为单位的持续时间?.

回答by Gregor

you can use the DurationFormatUtilsfrom commons-lang3-time (for minutes you have to use "mm" as the format is the same as in SimpleDateFormat): DurationFormatUtils.formatDuration(interval.toMillis(), "HHH+mm")

您可以使用commons-lang3-time 中的DurationFormatUtils(对于分钟,您必须使用“mm”,因为格式与 中的格式相同SimpleDateFormat): DurationFormatUtils.formatDuration(interval.toMillis(), "HHH+mm")

Sadly I found no way to exclude empty parts, like in my case days or hours could be 0, so I still had to roll my own.

可悲的是,我发现没有办法排除空的部分,比如在我的情况下,天或小时可能是 0,所以我仍然不得不自己动手。

Update: I have opened an issue for this on Apache commons.lang.time.DurationFormatUtils JIRA.

更新:我在 Apache commons.lang.time.DurationFormatUtils JIRA 上为此打开了一个问题