Instant和LocalDateTime有什么区别? [英] What's the difference between Instant and LocalDateTime?

查看:262
本文介绍了Instant和LocalDateTime有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道:




  • 即时是用于计算的技术时间戳表示(纳秒) 。

  • LocalDateTime 是日期/时钟表示,包括人类的时区。



最后IMO两者都可以作为大多数应用程序用例的类型。例如:目前我正在运行批处理作业,我需要根据日期计算下一次运行,我正在努力寻找这两种类型之间的优缺点(除了Instant的纳秒级精度优势和时区部分) of LocalDateTime)。



您能说出一些应用示例,其中只应使用Instant或LocalDateTime吗?



编辑:注意LocalDateTime关于精度和时区的误读文档

解决方案

推定错误




LocalDateTime是日期/时钟表示,包括人类的时区。


您的陈述不正确: A





A



想想



本地日期时间类, LocalDateTime LocalDate LocalTime ,是一种不同的生物。它们与任何一个地区或时区无关。它们与时间表无关。 他们没有实际意义,直到您将它们应用到某个地点以在时间轴上找到一个点。



例如,圣诞节从午夜开始在2015年12月25日是 LocalDateTime 。在巴黎不同时刻的午夜罢工比在蒙特利尔,在西雅图奥克兰

  LocalDate ld = LocalDate.of(2018,Month.DECEMBER,25); 
LocalTime lt = LocalTime.MIN; // 00:00:00
LocalTime ldt = LocalDateTime.of(ld,lt); //任何地方的圣诞节早晨。

另一个例子,Acme公司的政策是午餐时间从下午12:30开始全球工厂是 LocalTime 。为了具有真正的意义,您需要将其应用于时间线,以便在斯图加特 a>工厂或12:30在拉巴特工厂或12:30在悉尼工厂。



因此,对于商业应用,不经常使用本地类型,因为它们仅代表可能的日期或时间的一般概念,而不是时间线上的特定时刻。商业应用程序倾向于关注发票到达的确切时刻,运输的产品,雇用的员工或出租车离开车库。因此,业务应用开发人员几乎完全使用 Instant ZonedDateTime 。另一方面,您应该考虑使用 Local ... 类型来预订未来事件(例如:牙医约会),将来你可能会让政治家改善时区的风险他们经常这么做预警。






关于 java.time



java.time 框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如 java.util.Date 日历 ,& SimpleDateFormat



Joda-Time 项目,现在位于维护模式,建议迁移到 java.time 课程。



要了解更多信息,请参阅 Oracle教程 。并搜索Stack Overflow以获取许多示例和解释。规范是 JSR 310



您可以直接与数据库交换 java.time 对象。使用符合 JDBC驱动程序 jeps / 170rel =noreferrer> JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql。* 类。



从哪里获取java.time班?





ThreeTen-Extra 项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,例如 间隔 YearWeek YearQuarter 更多


I know that:

  • Instant is rather a "technical" timestamp representation (nanoseconds) for computing.
  • LocalDateTime is rather date/clock representation including time-zones for humans.

Still in the end IMO both can be taken as type for most application use-cases. As example: Currently I am running a batch job where I need to calculate a next run based on dates and I am struggling to find a pros/cons between these two types (apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime).

Can you name some application examples, where only Instant or LocalDateTime should be used?

Edit: Beware misread documentations for LocalDateTime regarding precision and time-zone

解决方案

Incorrect Presumption

LocalDateTime is rather date/clock representation including time-zones for humans.

Your statement is incorrect: A LocalDateTime has no time zone. Having no time zone is the entire point of that class.

To quote that class’ doc:

This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

So Local… means "not zoned".

Instant

An Instant is a moment on the timeline in UTC, a count of nanoseconds since the epoch of the first moment of 1970 UTC (basically, see class doc for nitty-gritty details). Since most of your business logic, data storage, and data exchange should be in UTC, this is a handy class to be used often.

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

ZoneId

A ZoneId is a time zone.

A time zone is an offset of so many hours and minutes away from UTC. A new day dawns earlier in Paris than in Montréal, for example. So we need to move the clock’s hands to better reflect noon (when the Sun is directly overhead) for a given region. The further away eastward/westward from the UTC line in west Europe/Africa the larger the offset.

Plus, a time zone is a set of rules for handling adjustments and anomalies as practiced by a local community or region. The most common anomaly is the all-too-popular lunacy known as Daylight Saving Time (DST).

A time zone has the history of past rules, present rules, and rules confirmed for the near future.

These rules change more often than you might expect. Be sure to keep your date-time library's rules, usually a copy of the 'tz' database, up to date. Keeping up-to-date is easier than ever now in Java 8 with Oracle releasing a Timezone Updater Tool.

Use proper time zone names. These names take the form of continent plus a SLASH plus a city or region. Avoid the 3-4 letter codes such as EST or IST. They are neither standardized nor unique. They further confuse the messiness of DST.

Time Zone = Offset + Rules of Adjustments

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;

Sometimes we have only an offset without the rules. Java provides the ZoneOffset for this purpose, a subclass of ZoneId. Note the handy constant defined there, ZoneOffset.UTC.

ZoneOffset offset = ZoneOffset.of( -5 , 0 ) ;  // "-05:00"

ZonedDateTime

Think of ZonedDateTime conceptually as an Instant with an assigned ZoneId.

ZonedDateTime = ( Instant + ZoneId )

Nearly all of your backend, database, business logic, data persistence, data exchange should all be in UTC. But for presentation to users you need to adjust into a time zone expected by the user. This is the purpose of the ZonedDateTime class and the formatter classes used to generate String representations of those date-time values.

ZonedDateTime zdt = instant.atZone( z ) ;

LocalDateTime, LocalDate, LocalTime

The "local" date time classes, LocalDateTime, LocalDate, LocalTime, are a different kind of critter. The are not tied to any one locality or time zone. They are not tied to the timeline. They have no real meaning until you apply them to a locality to find a point on the timeline.

For example, "Christmas starts at midnight on the 25th of December 2015" is a LocalDateTime. Midnight strikes at different moments in Paris than in Montréal, and different again in Seattle and in Auckland.

LocalDate ld = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
LocalTime lt = LocalTime.MIN ;   // 00:00:00
LocalTime ldt = LocalDateTime.of( ld , lt ) ;  // Xmas morning anywhere. 

Another example, "Acme Company has a policy that lunchtime starts at 12:30 PM at each of its factories worldwide" is a LocalTime. To have real meaning you need to apply it to the timeline to figure the moment of 12:30 at the Stuttgart factory or 12:30 at the Rabat factory or 12:30 at the Sydney factory.

So for business apps, the "Local" types are not often used as they represent just the general idea of a possible date or time not a specific moment on the timeline. Business apps tend to care about the exact moment an invoice arrived, a product shipped for transport, an employee was hired, or the taxi left the garage. So business app developers use Instant and ZonedDateTime almost exclusively. On the other hand you should consider using the Local… types for booking future events (ex: Dentist appointments) far enough out in the future where you risk politicians refining the time zone with little forewarning as they so often do.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

这篇关于Instant和LocalDateTime有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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