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

问题描述 投票:-7回答:2

使用新的Java 8 DateTime API(java.time),我们如何检查“最后”捕获时间是否比配置的秒数更长?

例...

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

if (last captured time is older then 30 seconds) then
    do something
java date java-8 java-time
2个回答
9
投票

tl;dr

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 

Details

Instant类代表UTC时间轴上的一个时刻,分辨率为纳秒。

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

Duration代表以秒和nanoseconds为单位的时间跨度。

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

提取整秒的数量。

long secondsElapsed = d.getSeconds() ;

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

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

相比。

if( secondsElapsed > limit ) { … }

0
投票

持续时间......

Duration duration = Duration.between(LocalDateTime.now(), LocalDateTime.now().plusSeconds(xx));
System.out.println(duration.getSeconds());
© www.soinside.com 2019 - 2024. All rights reserved.