tl;博士
Instant // Represents a moment as seen in UTC.
.ofEpochMilli( yourCount ) // Convert a count of milliseconds since 1970-01-01T00:00Z to an `Instant` object.
.isBefore( // Compares one `Instant` object to another.
Instant
.now() // Capture the current moment as seen in UTC (an offset of zero).
.minus( // Instantiate another `Instant` object for another moment, per immutable objects pattern.
Duration.ofHours( 48 ) // Define a span-of-time, not attached to the timeline, on a scale of hours-minutes-seconds.
) // Returns another `Instant` object.
) // Returns `boolean` primitive.
问题 1
如何确定我的代码中这是否超过 2 天?
将您的System.currentTimeMillis() long 整数解析为Instant。
Instant instant = Instant.ofEpochMilli( 1_628_125_542_977L ) ;
你显然想回到 48 小时。
Duration fortyEightHours = Duration.ofHours( 48 ) ;
Instant ago48Hours = Instant.now().minus( fortyEightHours ) ;
比较。
boolean momentIsMoreThan48HoursAgo = instant.isBefore( ago48Hours ) ;
问题 2
有没有更好的方法在创建期间分配时间戳而不是使用 system.currentTimeMillis ?
是的,更好的方法是Instant。
我建议您使用 Instant 类而不是 System.currentTimeMillis()。根据 Java 实现,您可以期望以毫秒或微秒的分辨率捕获当前时刻。
Instant now = Instant.now() ;
String outputIso8601 = now.toString() ;
long millisSinceEpoch = now.toEpochMilli() ;
除非您非常需要紧凑的数据,否则我建议您使用标准ISO 8601 格式的字符串而不是神秘数字来序列化日期时间值。
目前,格式为:2021-08-04T23:06:06Z,其中T 将年月日与时间分开,Z 表示 +00:00 与 UTC 的偏移量零。
问题 3
System.currentTimeMillis() 不是机器不可知论者,它是否提供 UTC 时间?
我不知道您所说的“机器不可知论”是什么意思。该调用确实会跟踪时间,并且它确实取决于正确设置主机的硬件时钟。
至于 UTC 时间,是的,方法 System.currentTimeMillis() 被记录为返回自 1970 年第一刻的 epoch reference 以来的 milliseconds 的数量(给或取,取决于主机硬件时钟的分辨率) offset-from-UTC 为零时分秒,1970-01-01T00:00Z,同时忽略 leap seconds。
Instant 类的作用相同,但可以用nanoseconds 的更精细粒度而不是毫秒来表示时刻。为了捕捉当前时刻,传统的计算机硬件时钟目前只能精确到毫秒到microseconds,而不是纳秒。
所有这些都已经在 Stack Overflow 上多次介绍过。 Search 了解更多。