比较用户定义的时间和当前时间 Java
我正在尝试将 HH:MM 格式的用户定义时间与无限循环中的当前时间进行比较.当它们相等时,应该发生一些动作.
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.
我使用了以下代码:
//taking user input
DateFormat sdf = new SimpleDateFormat("hh:mm");
String time = jFormattedTextField1.getText();
userTime = sdf.parse(time);
//taking current time
Date timeNow = new Date();
while (true){
if (timeNow.equals(userTime)){
System.out.println("The time equals, task is done!");
ChangingWindow window = new ChangingWindow(chosenColor);
当我打印这两个时间点时,我收到以下信息:
When I print these 2 time points I recieve the following:
用户时间:Thu Jan 01 10:35:00 CET 1970
User time: Thu Jan 01 10:35:00 CET 1970
当前时间:2015 年 9 月 29 日星期二 10:33:21 CEST
Current time: Tue Sep 29 10:33:21 CEST 2015
当前时间显然没问题,但对于用户定义的时间,他不断返回纪元.如果有人有任何建议,我将不胜感激!
Current time is obviously ok but for user defined time he keeps returning epoch. If anybody has any suggestion I would be grateful!
推荐答案
如果你只想比较时间HH:MM
,我建议使用LocalTime
:
If you only want to compare time HH:MM
, I would suggest to use LocalTime
:
"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)) { ... }
回应您的评论
userTime
和 timeNow
不会更新,然后在每次迭代中您总是比较相同的值.结果不会改变.您需要在 while
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
无论如何,我不能将 while (true)
视为一个好主意.我不知道您需要实现什么,但是如果您想等到达到用户时间,那么我将确定在那之前剩余的时间并让进程休眠这段时间.比如:
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);
相关文章