I am currently trying to fix an issue with my Java Code. Essentially, I have to variables: currentTime
of Type Instant
and activeAfterSecond
of type Duration
(from the java.time package).
Basically what I want to do is check whether currentTime has already passed the duration (or reached it). So in pseudocode something like this:
if(currentTime >= duration){
// do something
}
Obviously something like this does not work, as Instants and Durations cannot be compared to one another. I have been trying to figure out what method from the java.time.Instant and java.time.Duration packages would be best for comparing (e.g. using something like getSeconds()
from the Duration package) but haven't been able to find a proper, feasible solution.
Does anyone have any idea how I could solve this issue? Help would be appreciated!
(based on what Diego replied)
Duration startAndCurrentDur = Duration.between(startTime, currentTime);
Duration activeAfterSecond = Duration.ofSeconds(5); // just an example
if(startAndCurrentDur.compareTo(activeAfterSecond) >= 0){ //enter if branch when activeAfterSecond equal or greater than startAndCurrentDur
// do something
}
You need another Instant
variable, with the lastTime
(the currentTime
of a previous step). Then, you may try something like this:
if (Duration.between (lastTime, currentTime).compareTo (duration) > 0) {
// do Something
lastTime = currentTime;
}
Note: edited for using compareTo().