tl;博士
您无法将LocalDateTime 与分配时区(或与UTC 的偏移量)之前的某个时刻进行比较。
org.threeten.extra.Interval // Represents a span-of-time attached to the timeline, as a pair of `Instant` objects, a pair of moments in UTC.
.of (
myLocalDateTimeStart
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Determine a moment by assigning an time zone to a `LocalDateTime` to produce a `ZonedDateTime`, from which we extract an `Instant` to adjust into UTC.
.toInstant() ,
myLocalDateTimeStop
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Returns a `ZonedDateTime` object.
.toInstant() // From the `ZonedDateTime`, extract a `Instant` object.
) // Returns `Interval` object.
.contains(
Instant.ofEpochMilli( 1_532_463_173_752L ) // Parse a count of milliseconds since 1970-01-01T00:00:00Z as a moment in UTC, a `Instant` object.
) // Returns a boolean.
详情
比较 epoch 毫秒和 LocalDateTime 在 java 中的时间
你不能。这种比较不合逻辑。
LocalDateTime不代表一个时刻,不是时间线上的一个点。 LocalDateTime 代表在大约 26-27 小时范围内的潜在时刻,即世界各地的时区范围。
因此,除非您将其置于时区的上下文中,否则它没有真正的意义。如果该特定日期和时间在该区域中无效,例如在 Daylight Saving Time (DST) 切换期间或在其他一些此类异常期间,ZonedDateTime 类会调整。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = myLocalDateTime.atZone( z ) ;
为了进行比较,我们将通过从您的开始和停止 ZonedDateTime 对象中提取 Instant 对象来调整为 UTC。
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
现在将自 1970 年第一时刻的纪元参考以来的毫秒数解析为 Instant。 Instant 具有更精细的分辨率,纳秒级。
Instant instant = Instant.ofEpochMilli( 1_532_463_173_752L ) ;
比较以查看您的纪元毫秒是否代表我们停止和开始Instant 对象之间的时刻。通常在日期时间工作中,Half-Open 方法是最好的,其中开头是inclusive,而结尾是exclusive。
提示:说“等于或之后”的更简短的说法是说“不在之前”。
boolean inRange = ( ! instant.isBefore( start ) ) && instant.isBefore( stop ) ;
为了使这项工作更容易,请将ThreeTen-Extra 库添加到您的项目中。使用Interval 类。
Interval interval = Interval.of( start , stop ) ;
boolean inRange = interval.contains( instant ) ; // Uses Half-Open approach to comparisons.
提示:如果您打算跟踪时刻,则根本不应该使用 LocalDateTime 类。相反,请使用 Instant、OffsetDateTime 和 ZonedDateTime 类。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。