我想的名字org.joda.time.LocalDate
有点令人困惑。文档说:
LocalDate
is an immutable datetime class representing a date without a time zone.
比较
org.joda.time.DateTime
说:A
DateTime
calculates its fields with respect to a time zone.
我总是把这两个混淆,所以我希望有人能告诉我为什么这些名字应该有意义。
这是我的直觉:A 本地 日期或时间对象将代表一个时间点,但与位置有关。因此它应该包含时区信息,因为时区还为您提供某种位置信息。无论如何,与没有时区的情况相比,您对某人所在位置的了解要多一些。
日期时间,至少听起来是这样,应该只代表日期和时间。从这个意义上说,它只是
long
自 1970 年 1 月 1 日星期四 00:00:00 协调世界时 (UTC) 以来的值。那么为什么实际上是相反的呢?每次我与时间戳有关时,这种命名都会让我感到困惑。有人可以解释一下吗?
更新:
由 user 发布的有趣链接:https://sourceforge.net/p/threeten/mailman/message/29962542/
最佳答案
术语
您的直觉与 Joda-Time 和 java.time 使用的术语相反。
两个框架都有一个名为 LocalDate
的类。表示没有时间和时区的仅日期值。 “本地”的意思是“可以是任何地方,而不是任何特定的地方”。
“本地……”类(class)只是一个时期的粗略概念。他们不在时间线上。在您应用时区或从 UTC 偏移以获得时间线上的实际时刻之前,它们没有真正的意义。当您看到“Local”时,您会认为:“在我们应用时区之前,这个值没有任何意义”。
例如,我们说今年圣诞节是 2016-12-25。但在任何特定时刻,世界各地的日期都不相同。例如,巴黎比蒙特利尔更早地迎来新的一天。因此,要获得巴黎圣诞节开始的那一刻,您必须申请 Europe/Paris
时区并获得当天的第一个时刻。第一个时刻将由 DateTime
表示在 Joda-Time 和 ZonedDateTime
(或 OffsetDateTime
)在 java.time 中。
例如,在 java.time 中:
LocalDate xmas2016 = LocalDate.of( 2016 , 12 , 25 );
ZonedDateTime xmas2016FirstMomentMontreal = xmas2016.atStartOfDay( ZoneId.of( "America/Montreal" ) );
时间在 java.time 框架中,UTC 时间线上的时刻由
Instant
表示。类(class)。Instant now = Instant.now();
应用时区,ZoneId
, 获得 ZonedDateTime
.ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
如果您所拥有的只是UTC 偏移量而不是完整时区,则不要使用OffsetDateTime
而不是 ZonedDateTime
.你可以这样想:
Instant + ZoneId -> ZonedDateTime
Instant + ZoneOffset ->OffsetDateTime
此信息已在 StackOverflow 上讨论了数百次。请搜索以了解更多信息并查看许多示例代码。
关于date - 为什么 org.joda.time.LocalDate 是没有时区的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35539025/