我知道.NET我可以这样做:
DateTime test = DateTime.Now;
if (test >= (pastTime + TimeSpan.FromSeconds(15)) {
doSomething();
}
什么是Java等价物?
答案 0 :(得分:10)
对于这个简单的检查,我建议只使用时间戳(以毫秒为单位),而不是使用java.util.Date或其他一些类:
long test = System.currentTimeMillis();
if(test >= (pastTime + 15*1000)) { //multiply by 1000 to get milliseconds
doSomething();
}
请注意,pastTime
变量也必须,以毫秒为单位。
不幸的是,没有合适的“内置”java类来处理时间跨度。为此,请查看Joda Time库。
答案 1 :(得分:1)
在我看来,你可以把它放在一个循环中。我会以这种方式实现它。
long initTime = System.currentTimeMillis();
boolean timeElapsed = false;
while(timeElapsed){
if(System.currentTimeMillis - initTime > 15000 ){
timeElapsed = true
}else{
doSomethingElse();
Thread.sleep(500)
}
}
doSomething()
答案 2 :(得分:0)
我能够通过在我的项目中使用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;
}
这将检查Time
和datetime1
datetime2
5 isGreaterThan
之间的Minutes
间隔时间。将属性更改为Seconds
。你知道这会更容易。
答案 3 :(得分:0)
自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();
}
}