[英]How to check if X seconds has passed in Java?
我知道在.NET 中我可以這樣做:
DateTime test = DateTime.Now;
if (test >= (pastTime + TimeSpan.FromSeconds(15)) {
doSomething();
}
Java 等價物是什么?
對於這個簡單的檢查,我建議只使用時間戳(以毫秒為單位)而不是使用 java.util.Date 或其他一些類:
long test = System.currentTimeMillis();
if(test >= (pastTime + 15*1000)) { //multiply by 1000 to get milliseconds
doSomething();
}
請注意,過去pastTime
變量也必須以毫秒為單位。
不幸的是,沒有合適的“內置”java 類來處理時間跨度。 為此,請查看Joda Time庫。
更新:Java 8 引入了java.time 包,使用它代替外部 joda 時間。
自 JDK8 以來的 Java 時間庫可以執行以下操作:
import java.time.Duration
import java.time.Instant
class MyTimeClass {
public static void main(String[] args) {
Instant then = Instant.now();
Duration threshold = Duration.ofSeconds(3);
// allow 5 seconds to pass
Thread.sleep(5000);
assert timeHasElapsedSince(then, threshold) == true;
}
public static boolean timeHasElapsedSince(Instant then, Duration threshold) {
return Duration.between(then, Instant.now()).toSeconds() > threshold.toSeconds();
}
}
在我看來你可以把它放在一個while循環中。 我會以這種方式實現它。
long initTime = System.currentTimeMillis();
boolean timeElapsed = false;
while(timeElapsed){
if(System.currentTimeMillis - initTime > 15000 ){
timeElapsed = true
}else{
doSomethingElse();
Thread.sleep(500)
}
}
doSomething()
我能夠通過在我的項目中使用 JodaTime 庫來實現這一點。 我想出了這個代碼。
String datetime1 = "2012/08/24 05:22:34";
String datetime2 = "2012/08/24 05:23:28";
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime time1 = format.parseDateTime(datetime1);
DateTime time2 = format.parseDateTime(datetime2);
Minutes Interval = Minutes.minutesBetween(time1, time2);
Minutes minInterval = Minutes.minutes(5);
if(Interval.isGreaterThan(minInterval)){
return true;
}
else{
return false;
}
這將檢查datetime1
和datetime2
之間的Time
間隔是否isGreaterThan
5 Minutes
。 將該屬性更改為Seconds
。 你會更容易知道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.