使用新的Java 8 DateTime API(java.time),我们如何检查“最后”捕获时间是否早于配置的秒数?
示例...
上次拍摄时间:13:00:00 当前时间:13:00:31
if (last captured time is older then 30 seconds) then
do something
答案 0 :(得分:9)
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
类代表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 ) { … }
答案 1 :(得分:0)
持续时间......
Duration duration = Duration.between(LocalDateTime.now(), LocalDateTime.now().plusSeconds(xx));
System.out.println(duration.getSeconds());
答案 2 :(得分:0)
还有 getSeconds()
方法:
Instant start = Instant.now()
// Do something
Instant end = Instant.now()
if (Duration.between(start, end).getSeconds() > 30) {
// do something else
}