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