Compare user defined time and current time Java

送分小仙女□ 提交于 2019-12-02 07:06:26

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

If you don't set YEAR, MONTH, DAY it starts from 1/1/1970.

So basically you need to set YEAR, MONTH, DAY to the date you like.

In your code you are creating a new Date setting only hour and minutes and leaving the other values to default.

From javadoc:

This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information. For example, the year value of the parsed Date is 1970 with GregorianCalendar if no year value is given from the parsing operation.

Tom

This is OPs(*) fixed code following Tobías's instructions:

//get user time and current time
String time = jFormattedTextField1.getText();
LocalTime userTime1 = LocalTime.parse(time);
LocalTime timeNow = LocalTime.now().truncatedTo(ChronoUnit.SECONDS);

//calculate the diff in seconds
int timeDur = (int)Duration.between(timeNow, userTime1).getSeconds();
//start the timer object using this difference
Countdown countdown = new Countdown (timeDur);

(*) Extracted from the edited question, because it doesn't belong there (see this meta discussion)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!