Java 8 日期时间 API (java.time) 和 Joda-Time 之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24631909/
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
Differences between Java 8 Date Time API (java.time) and Joda-Time
提问by Zack
I know there are questions relating to java.util.Dateand Joda-Time. But after some digging, I couldn't find a thread about the differences between the java.time API(new in Java 8, defined by JSR 310) and Joda-Time.
我知道有关于java.util.Date和 Joda-Time 的问题。但是经过一番挖掘,我找不到关于java.time API(Java 8 中的新内容,由JSR 310定义)和Joda-Time之间差异的线索。
I have heard that Java 8's java.time API is much cleaner and can do much more than Joda-Time. But I cannot find examples comparing the two.
我听说 Java 8 的 java.time API 更简洁,并且可以比 Joda-Time 做更多的事情。但我找不到比较两者的例子。
- What can java.time do that Joda-Time cannot?
- What can java.time do better than Joda-Time?
- Is the performance better with java.time?
- java.time 能做什么而 Joda-Time 不能?
- java.time 有什么比 Joda-Time 更好的地方?
- java.time 的性能更好吗?
采纳答案by Meno Hochschild
Common features
共同特征
a) Both libraries use immutable types. Joda-Time also offers additional mutable types like MutableDateTime
.
a) 两个库都使用不可变类型。Joda-Time 还提供了额外的可变类型,如MutableDateTime
.
b) Furthermore: Both libraries are inspired by the design study "TimeAndMoney" from Eric Evansor ideas from Martin Fowler about domain driven styleso they strive more or less for a fluent programming style(although not always perfect ;-)).
b) 此外:这两个库的灵感都来自 Eric Evans的设计研究“TimeAndMoney”或Martin Fowler 的关于领域驱动风格的想法,因此他们或多或少地为流畅的编程风格而努力(尽管并不总是完美的 ;-))。
c) With both libraries we get a real calendar date type (called LocalDate
), a real wall time type (called LocalTime
) and the composition (called LocalDateTime
). That is a very big win compared with old java.util.Calendar
and java.util.Date
.
c) 通过这两个库,我们得到了一个真实的日历日期类型(称为LocalDate
)、一个真实的挂钟时间类型(称为LocalTime
)和组合(称为LocalDateTime
)。与旧的java.util.Calendar
和java.util.Date
..相比,这是一个非常大的胜利。
d) Both libraries use a method-centric approach meaning they encourage the user to use getDayOfYear()
instead of get(DAY_OF_YEAR)
. This causes a lot of extra methods compared with java.util.Calendar
(although latter is not type-safe at all due to excessive use of ints).
d)两个库使用的方法为中心的方法意味着它们鼓励使用的用户getDayOfYear()
,而不是get(DAY_OF_YEAR)
。与java.util.Calendar
(尽管后者由于过度使用整数而根本不是类型安全的)相比,这会导致许多额外的方法。
Performance
表现
See the other answer by @OO7 pointing to the analysis of Mikhail Vorontsov although point 3 (exception catching) is probably obsolete - see this JDK-bug. The different performance (which is in general favour of JSR-310) is mainly due to the fact that the internal implementation of Joda-Timealways use a machine-time-like long-primitive (in milliseconds).
请参阅@OO7 指向 Mikhail Vorontsov 分析的另一个答案,尽管第 3 点(异常捕获)可能已过时 - 请参阅此 JDK-bug。不同的性能(通常有利于JSR-310)主要是由于Joda-Time的内部实现总是使用类似机器时间的 long-primitive(以毫秒为单位)。
Null
空值
Joda-Time often use NULL as default for system timezone, default locale, current timestamp etc. while JSR-310 almost always rejects NULL values.
Joda-Time 通常使用 NULL 作为系统时区、默认语言环境、当前时间戳等的默认值,而 JSR-310 几乎总是拒绝 NULL 值。
Precision
精确
JSR-310 handles nanosecondprecision while Joda-Time is limited to millisecondprecision.
JSR-310 处理纳秒精度,而 Joda-Time 仅限于毫秒精度。
Supported fields:
支持的字段:
An overview about supported fields in Java-8 (JSR-310) is given by some classes in the temporal-package (for example ChronoFieldand WeekFields) while Joda-Time is rather weak on this area - see DateTimeFieldType. The biggest lack of Joda-Time is here the absence of localized week-related fields. A common feature of both field implementation design is that both are based on values of type long (no other types, not even enums).
时间包中的一些类(例如ChronoField和WeekFields)给出了 Java-8 (JSR-310) 中支持的字段的概述,而 Joda-Time 在这方面相当薄弱 - 请参阅DateTimeFieldType。Joda-Time 的最大不足是这里没有本地化的与周相关的字段。两种字段实现设计的一个共同特点是都基于 long 类型的值(没有其他类型,甚至没有枚举)。
Enum
枚举
JSR-310 offers enumslike DayOfWeek
or Month
while Joda-Time does not offer this because it was mainly developed in years 2002-2004 before Java 5.
JSR-310 提供了像or 之类的枚举DayOfWeek
,Month
而 Joda-Time 不提供这个,因为它主要是在Java 5之前的 2002-2004 年开发的。
Zone API
区域API
a) JSR-310 offers more timezone features than Joda-Time. Latter is not able to yield a programmatical access to the history of timezone offset transitions while JSR-310 is capable to do this.
a) JSR-310 提供了比 Joda-Time 更多的时区特性。后者无法以编程方式访问时区偏移转换的历史记录,而 JSR-310 能够做到这一点。
b) For your information: JSR-310 has moved its internal timezone repository to a new location and a different format. The old library folder lib/zi does not exist any more.
b) 供您参考:JSR-310 已将其内部时区存储库移至新位置和不同格式。旧的库文件夹 lib/zi 不再存在。
Adjuster vs. Property
调整者与财产
JSR-310 has introduced the TemporalAdjuster
-interface as a formalized way to externalize temporal calculations and manipulations, especially for library or framework-writers this is a nice and relative easy way to embed new extensions of JSR-310 (a kind of equivalent to static helper classes for former java.util.Date
).
JSR-310 引入了TemporalAdjuster
-interface 作为外部化时间计算和操作的形式化方式,特别是对于库或框架编写者,这是嵌入 JSR-310 新扩展的一种很好且相对简单的方法(一种等效于静态帮助器以前的课程java.util.Date
)。
For most users however, this feature has very limited value because the burden to write code is still with the user. Built-in solutions based on the new TemporalAdjuster
-concept are not so many, there is currently only the helper class TemporalAdjusters
with a limited set of manipulations (and the enums Month
or other temporal types).
然而,对于大多数用户来说,这个特性的价值非常有限,因为编写代码的负担仍然在用户身上。基于新TemporalAdjuster
概念的内置解决方案并不多,目前只有辅助类TemporalAdjusters
具有有限的操作集(以及枚举Month
或其他时间类型)。
Joda-Time offers a field-package but practice has shown evidence that new field implementations are very hard to code. On the other side Joda-Time offers so-called properties which make some manipulations much easier and more elegant than in JSR-310, for example property.withMaximumValue().
Joda-Time 提供了一个字段包,但实践表明,新的字段实现很难编码。另一方面,Joda-Time 提供了所谓的属性,这使得一些操作比 JSR-310 更容易和更优雅,例如property.withMaximumValue()。
Calendar systems
日历系统
JSR-310 offers 4 extra calendar systems. The most interesting one is Umalqura(used in Saudi Arabia). The other 3 are: Minguo(Taiwan), Japanese (only the modern calendar since 1871!) and ThaiBuddhist(only correct after 1940).
JSR-310 提供了 4 个额外的日历系统。最有趣的是Umalqura(在沙特阿拉伯使用)。其他 3 种是:民国(台湾)、日本(仅自 1871 年以来的现代日历!)和泰国佛教(仅在 1940 年之后更正)。
Joda-Time offers an Islamic calendarbased on calculatory base - not a sighting-based calendar like Umalqura. Thai-Buddhist is also offered by Joda-Time in a similar form, Minguo and the japanese one not. Otherwise Joda-Time offers coptic and ethiopic calendar, too (but without any support for internationalization).
Joda-Time 提供基于计算基础的伊斯兰日历- 而不是像 Umalqura 那样基于目击的日历。Joda-Time 也以类似的形式提供 Thai-Buddhist,Minguo 和 Japan 不提供。否则 Joda-Time 也提供科普特和埃塞俄比亚日历(但不支持任何国际化)。
More interesting for Europeans: Joda-Time also offers a Gregorian, Julianand mixed-gregorian-julian calendar. However, the practical value for real historical calculations is limited because important features like different year starts in date history are not supported at all (the same criticism is valid for old java.util.GregorianCalendar
).
对欧洲人来说更有趣:Joda-Time 还提供公历、儒略历和混合公历-儒略历。然而,真实历史计算的实用价值是有限的,因为根本不支持日期历史中不同年份开始等重要特征(同样的批评对 old 有效java.util.GregorianCalendar
)。
Other calendars like Hebrewor Persianor Hinduare completely missing in both libraries.
两个图书馆中都完全没有其他日历,如希伯来语、波斯语或印度教日历。
Epoch days
大纪元
JSR-310 has the class JulianFieldswhile Joda-Time (version 2.0) offers some helper methods in the class DateTimeUtils.
JSR-310 具有JulianFields类,而 Joda-Time(2.0 版)在类DateTimeUtils 中提供了一些辅助方法。
Clocks
时钟
JSR-310 has no interface (a design mistake) but an abstract class java.time.Clock
which can be used for any clock dependency injection. Joda-Time offers the interface MillisProviderand some helper methods in DateTimeUtilsinstead. So this way Joda-Time is also capable of supporting test-driven models with different clocks (mocking etc.).
JSR-310 没有接口(设计错误),而是一个抽象类java.time.Clock
,可用于任何时钟依赖注入。Joda-Time 提供接口MillisProvider和DateTimeUtils 中的一些辅助方法。因此,通过这种方式 Joda-Time 也能够支持具有不同时钟(模拟等)的测试驱动模型。
Duration arithmetic
工期算术
Both libraries support the calculation of time distances in one or more temporal units. However, when handling single-unit-durations the JSR-310-style is obviously nicer (and long-based instead of using int):
两个库都支持以一个或多个时间单位计算时间距离。但是,在处理单单元持续时间时,JSR-310 样式显然更好(并且基于长而不是使用 int):
JSR-310 => long days = ChronoUnit.DAYS.between(date1, date2);
JSR-310 => long days = ChronoUnit.DAYS.between(date1, date2);
Joda-Time => int days = DAYS.daysBetween(date1, date2).getDays();
乔达时间 => int days = DAYS.daysBetween(date1, date2).getDays();
Handling of multiple-unit-durations are also different. Even the calculation results can differ - see this closed Joda-Time issue. While JSR-310 use a very simple and limited approach to use just the classes Period
(duration based on years, months and days) and Duration
(based on seconds and nanoseconds), Joda-Time uses a more sophisticated way using the class PeriodType
in order to control in which units a duration (Joda-Time call it "Period") shall be expressed. While the PeriodType
-API is somehow awkward to use a similar way is not offered by JSR-310 at all. Especially it is not yet possible in JSR-310 to define mixed date and time durations (based on days and hours for example). So be warned if it comes to migration from one library to another. The libraries in discussion are incompatible - despite of partially same class names.
多单元持续时间的处理也不同。甚至计算结果也可能不同 - 请参阅此已关闭的Joda-Time 问题。虽然 JSR-310 使用一种非常简单且有限的方法来仅使用类Period
(持续时间基于年、月和日)和Duration
(基于秒和纳秒),但 Joda-Time 使用更复杂的方式使用类PeriodType
来控制应以哪个单位表示持续时间(Joda-Time 称其为“期间”)。虽然PeriodType
-API 有点尴尬,使用 JSR-310 根本没有提供的类似方式。特别是在 JSR-310 中还不可能定义混合的日期和时间持续时间(例如基于天和小时)。因此,如果涉及从一个库迁移到另一个库,请注意。讨论中的库是不兼容的——尽管类名部分相同。
Intervals
间隔
JSR-310 does not support this feature while Joda-Time has limited support. See also this SO-answer.
JSR-310 不支持此功能,而 Joda-Time 支持有限。另请参阅此SO-answer。
Formatting and Parsing
格式化和解析
Best way to compare both libraries is to view the equal-named classes DateTimeFormatterBuilder(JSR-310) and DateTimeFormatterBuilder(Joda-Time). The JSR-310-variant is a little bit more powerful (can also handle any kind of TemporalField
provided the field implementor has managed to code some extension points like resolve()). Most important difference is however - in my opinion:
比较这两个库的最佳方法是查看同名类DateTimeFormatterBuilder(JSR-310) 和DateTimeFormatterBuilder(Joda-Time)。JSR-310-variant 更强大一点(也可以处理任何类型,TemporalField
前提是字段实现者设法编写了一些扩展点,如resolve())。然而,最重要的区别是 - 在我看来:
JSR-310 can much better parse timezone names (format pattern symbol z) while Joda-Time could not do this at all in its earlier versions and now only in a very limited way.
JSR-310 可以更好地解析时区名称(格式模式符号 z),而 Joda-Time 在其早期版本中根本无法做到这一点,现在只能以非常有限的方式做到这一点。
Another advantage of JSR-310 is support for standalone month names which is important in languages like Russian or Polish etc. Joda-Time has no access to such resources- not even on Java-8 platforms.
JSR-310 的另一个优点是支持独立的月份名称,这在俄语或波兰语等语言中很重要。 Joda-Time无法访问此类资源- 即使在 Java-8 平台上也不行。
The pattern syntax in JSR-310 is also more flexible than in Joda-Time, allows for optional sections (using square brackets), is more orientated towards CLDR-standard and offers padding (letter symbol p) and more fields.
JSR-310 中的模式语法也比 Joda-Time 更灵活,允许可选部分(使用方括号),更面向 CLDR 标准并提供填充(字母符号 p)和更多字段。
Otherwise it should be noted that Joda-Time can format durations using PeriodFormatter. JSR-310 cannot do this.
否则应该注意 Joda-Time 可以使用PeriodFormatter格式化持续时间。JSR-310 不能这样做。
Hope this overview helps. All the gathered information is mainly there due to my efforts and investigations how to design and implement a better date-and-time library (nothing is perfect).
希望这个概述有帮助。所有收集到的信息主要是由于我的努力和调查如何设计和实现一个更好的日期和时间库(没有什么是完美的)。
Update from 2015-06-24:
2015-06-24 更新:
Meanwhile I have found the time to write and publish a tabular overviewfor different time libraries in Java. The tables also contain a comparison between Joda-Time v2.8.1 and Java-8 (JSR-310). It is more detailed than this post.
同时,我有时间为Java 中的不同时间库编写和发布表格概述。这些表还包含 Joda-Time v2.8.1 和 Java-8 (JSR-310) 之间的比较。比这个帖子详细。
回答by OO7
Java 8 Date/Time :
Java 8 日期/时间:
- Java 8 classes are built around the human time. It makes them fast for human datetime arithmetics/conversion.
- Date/time component getters like
getDayOfMonth
have O(1) complexity in Java 8 implementation. - Parsing of
OffsetDateTime
/OffsetTime
/ZonedDateTime
is very slow in Java 8 ea b121 due to exceptions thrown and caught internally in the JDK. - A set of packages:
java.time.*
,java.time.chrono.*
,java.time.format.*
,java.time.temporal.*
,java.time.zone.*
- Instants (timestamps) Date and Time Partial Date and Time Parser and Formatter Time zones Different chronologies (calendars).
- Existing classes have issues like Date has no support for I18N or L10N. They are mutable!
- Simpler & more robust.
- Clocks can be injected.
- Clocks can be created with various properties - Static clocks, Mocked clocks, Low-precision clocks (whole seconds, whole minutes, etc).
- Clocks can be created with specific time zones.
Clock.system(Zone.of("America/Los_Angeles"))
. - Makes code handling date and time testable.
- Makes tests independent of timezone.
- Java 8 类是围绕人类时间构建的。它使它们能够快速进行人类日期时间算术/转换。
- 日期/时间组件 getter
getDayOfMonth
在 Java 8 实现中具有 O(1) 复杂度。 - 解析
OffsetDateTime
/OffsetTime
/ZonedDateTime
是Java 8 EA B121非常缓慢,由于在JDK抛出和捕获内部例外。 - 一组包:
java.time.*
,java.time.chrono.*
,java.time.format.*
,java.time.temporal.*
,java.time.zone.*
- 瞬间(时间戳) 日期和时间 部分日期和时间 解析器和格式化程序 时区 不同的年表(日历)。
- 现有类存在诸如 Date 不支持 I18N 或 L10N 之类的问题。它们是可变的!
- 更简单、更健壮。
- 可以注入时钟。
- 可以使用各种属性创建时钟 - 静态时钟、模拟时钟、低精度时钟(整秒、整分钟等)。
- 可以创建具有特定时区的时钟。
Clock.system(Zone.of("America/Los_Angeles"))
. - 使代码处理日期和时间可测试。
- 使测试独立于时区。
Joda-Time :
乔达时间:
- Joda-Time is using machine time inside. A manual implementation based on int/long values would be much faster.
- Joda-Time getters require the computer-to-human time calculation on every getter call, which makes Joda-Time a bottleneck in such scenarios.
- It is composed of immutable classes it handles Instants, Date & Time, Partials, and Durations It is flexible It is well designed.
- Represents dates as instants. But a date&time may correspond to more than one instant. Overlap hour when daylight savings end. As well as not have any instant that corresponds to it at all. Gap hour when daylight starts. Has to perform complex computations for simple operations.
- Accepts nulls as valid values on most of its methods. Leads to subtle bugs.
- Joda-Time 在内部使用机器时间。基于 int/long 值的手动实现会快得多。
- Joda-Time getter 需要在每次 getter 调用时进行计算机到人的时间计算,这使得 Joda-Time 在这种情况下成为瓶颈。
- 它由处理 Instants、Date & Time、Partials 和 Durations 的不可变类组成它很灵活它设计得很好。
- 将日期表示为瞬间。但是一个日期和时间可能对应多个瞬间。夏令时结束时的重叠时间。以及根本没有与之对应的瞬间。白天开始时的间隙时间。必须为简单的操作执行复杂的计算。
- 接受空值作为其大多数方法的有效值。导致细微的错误。
For more detailed comparision see :-
有关更详细的比较,请参阅:-
Java 8 Date/Time library performance (as well as Joda-Time 2.3 and j.u.Calendar). & New Date & Time API in Java 8
Java 8 日期/时间库性能(以及 Joda-Time 2.3 和 juCalendar)。与 新的日期和时间API在Java中8