在 Java 8/jsr310 中格式化持续时间 [英] Formatting a Duration in Java 8 / jsr310
问题描述
我正在将一个项目从 Joda-Time 转换为 java8 的本机时间库,但遇到了障碍.
I am transitioning a project from Joda-Time to java8's native time libraries, and I have run into a snag.
我一直无法找到 Duration 的格式化程序.我想要一个自定义字符串格式,例如 HHH+MM,其中 75 小时 15 分钟的持续时间将格式化为 "75+15".
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".
通过转换为句点并使用PeriodFormatter,使用Joda-Time 很容易做到这一点,但是我在Java8 中找不到这种类型的类.我错过了什么吗?
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?
推荐答案
jsr-310 中没有 period/duration-formatter,与 JodaTime 不同.并非 JodaTime 的每个功能都被移植到 JSR-310(例如也不是 PeriodType).反过来,JSR-310 有一些 JodaTime 没有的功能(例如本地化的工作日数字或带有调整器的策略模式方法).
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).
Java 9 可能会引入某种内置的句点格式(从 S. Colebourne 阅读有关此内容的一些内容).
It might happen that Java 9 will introduce some kind of built-in period formatting (read something about this from S. Colebourne).
结论:JSR-310 和 JodaTime 并不完全兼容,因此可能需要做很多工作.我不会那么热衷于尽快移民.您是否需要 JodaTime 不提供的 JSR-310 特殊功能?
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?
附加说明:您还应该意识到 joda period(包括从年到秒的所有单位)与 jsr310-period(仅年、月、日)或 jsr310-duration(仅小时)不完全兼容、分、秒和小数秒).
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).
这篇关于在 Java 8/jsr310 中格式化持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!