开发者

How to check if X seconds has passed in Java?

I开发者_开发知识库 know in .NET I can do this:

DateTime test = DateTime.Now;
if (test >= (pastTime + TimeSpan.FromSeconds(15)) {
    doSomething();
}

What is the Java equivalent?


For this simple check I would advise to simply use the timestamp (in milliseconds) instead of using java.util.Date or some other classes:

long test = System.currentTimeMillis();
if(test >= (pastTime + 15*1000)) { //multiply by 1000 to get milliseconds
  doSomething();
}

Please note that the pastTime variable would also have to be in milliseconds.

Unfortunately, there are no suitable "built-in" java classes to deal with time spans. In order to do this, check out the Joda Time library.

UPDATE: Java 8 introduced the java.time package, use that instead of the external joda time.


The java time library since JDK8 can do something like:

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();
    }
}


In my opinion you can put it in a while cycle. I would implement it in this way.

long initTime = System.currentTimeMillis();
boolean timeElapsed = false;
while(timeElapsed){
  if(System.currentTimeMillis - initTime > 15000 ){
    timeElapsed = true
  }else{
    doSomethingElse();
    Thread.sleep(500)
  }
}
doSomething()


I was able to accomplish this by using a JodaTime Library in my project. I came out with this code.

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;
}

This will check if the Time Interval between datetime1 and datetime2 isGreaterThan 5 Minutes. Change the property to Seconds. It will be easier for you know.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜