Java 8 Date如何检查时间是否早于X秒?

use*_*024 -6 java date java-8 java-time

使用新的Java 8 DateTime API(java.time),我们如何检查"最后"捕获时间是否早于配置的秒集?

例...

上次拍摄时间:13:00:00当前时间:13:00:31

if (last captured time is older then 30 seconds) then
    do something
Run Code Online (Sandbox Code Playgroud)

Bas*_*que 9

TL;博士

Duration.between(
    myEarlierInstant ;       // Some earlier `Instant`. 
    Instant.now() ;          // Capture the current moment in UTC. 
)
.compareTo(                  // Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
    Duration.ofMinutes( 5 )  // A span of time unattached to the timeline. 
)
> 0 
Run Code Online (Sandbox Code Playgroud)

细节

Instant级表示时间轴上的时刻UTC在纳秒的分辨率.

Instant then = … ;
Instant now = Instant.now();
Run Code Online (Sandbox Code Playgroud)

A Duration表示以秒和纳秒为单位的时间跨度.

Duration d = Duration.between( then , now );
Run Code Online (Sandbox Code Playgroud)

提取整秒的数量.

long secondsElapsed = d.getSeconds() ;
Run Code Online (Sandbox Code Playgroud)

与你的限制相比.使用TimeUnit枚举转换而不是硬编码"魔术"数字.例如,将五分钟转换为几秒钟.

long limit = TimeUnit.MINUTES.toSeconds( 5 );
Run Code Online (Sandbox Code Playgroud)

相比.

if( secondsElapsed > limit ) { … }
Run Code Online (Sandbox Code Playgroud)