简体   繁体   中英

Difference between current time and future time in java

I am using Java Timer class for running certain task. For my program I will give starttime and endtime as parameters which will ask the java timer when to start and when to end the task.

While running my task, I want to get and check the difference between current time and endtime periodically and If current time equals endtime then cancel the task by calling timer.cancel() method.

My startTime and endTime parrameters time format are like this

String startTime = "12:00";
String endTime = "12:01";
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = format.parse(startTime);
Date date2 = format.parse(endTime);
long difference = date2.getTime() - date1.getTime();

I want to check the current time is equal to endtime.

But I want to check the condition that the current time is equal to end time and call the timer.cancel()

It may not be the time problem..

If comparing two Strings, you'd better use equals()

Try this :

if(currentTime.equals(endTime)) {
    timer.cancel();
}

您应该使用“ currentTime.equals(endTime)”函数比较字符串,而不是==运算符。“。equals”函数检查字符串的实际内容,==运算符检查两个对象的引用是否均相等,在您的情况下无效。

You want to check if the current time is equal to the end time - that is understood but to what level do you wish to check if it is equal - up to the minute, second or millisecond? Since if you compare by the millisecond or lower it is possible that you may never cancel even when the time may be same to the second.

If you want to check to the millisecond - just convert your end date to millis date.getTime() and subtract System.currentTimeMillis() - if the result is 0 it is same to the millisecond. If the difference is less than 1000 (1 * 1000) it is within the second. If it is less than 60000 (1 * 60 * 1000) it is within the minute.

May be, you just don't know how to get the endTime .

String startTime = "12:00";

SimpleDateFormat sDateFormat = new SimpleDateFormat(
            "hh:mm");
String endTime = sDateFormat.format(new java.util.Date());

if (startTime.equals(endTime)) {
    timer.cancel();
}

try, and good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM