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

Java 8 Date how to check if time is older then X seconds?

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

示例...

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

if (last captured time is older then 30 seconds) then
    do something

持续时间是...

Duration duration = Duration.between(LocalDateTime.now(), LocalDateTime.now().plusSeconds(xx));
System.out.println(duration.getSeconds());

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 

详情

Instant class represents a moment on the timeline in UTC 以纳秒为单位的分辨率。

Instant then = … ;
Instant now = Instant.now();

一个Duration represents a span of time in terms of seconds and nanoseconds.

Duration d = Duration.between( then , now );

提取整秒数。

long secondsElapsed = d.getSeconds() ;

与您的极限进行比较。使用 TimeUnit 枚举来转换而不是硬编码一个“魔法”数字。例如,将五分钟转换为秒数。

long limit = TimeUnit.MINUTES.toSeconds( 5 );

比较。

if( secondsElapsed > limit ) { … }

还有getSeconds()方法:

Instant start = Instant.now()
// Do something
Instant end = Instant.now()

if (Duration.between(start, end).getSeconds() > 30) {
    // do something else
}