Compare user defined time and current time Java

前端 未结 3 1164
甜味超标
甜味超标 2021-01-26 23:25

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

3条回答
  •  滥情空心
    2021-01-27 00:02

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

提交回复
热议问题