I am trying to compare user defined time in format HH:MM with current time in an infinite loop. When they are equal, some action should occur.
I have used following code
If you only want to compare time HH:MM
, I would suggest to use LocalTime:
"LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second."
"This class does not store or represent a date or time-zone. Instead, it is a description of the local time as seen on a wall clock."
LocalTime user = LocalTime.parse("12:55");
LocalTime now = LocalTime.now().truncatedTo(ChronoUnit.MINUTES);
if (user.equals(now)) { ... }
Edit: in answer to your comment
userTime
and timeNow
aren't updated, then in each iteration you are comparing always the same values. The result will not change. You need to update timeNow
inside the while
Anyway I can't think about while (true)
as a good idea. I don't know what you need to achieve but if you want to wait until the user time is reached, then I would determine the time remaining until then and sleep the process this amount of time. Something like:
long time = Duration.between(now, user).toMillils();
Thread.sleep(time);