简体   繁体   English

Java中当前时间和未来时间之间的时差

[英]Difference between current time and future time in java

I am using Java Timer class for running certain task. 我正在使用Java Timer类来运行某些任务。 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. 对于我的程序,我将提供starttime和endtime作为参数,这些参数将询问java计时器何时开始以及何时结束任务。

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. 在运行任务时,我想定期获取并检查当前时间与结束时间之间的差异,如果当前时间等于结束时间,则可以通过调用timer.cancel()方法取消任务。

My startTime and endTime parrameters time format are like this 我的startTimeendTime参数时间格式如下

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() 但是我想检查当前时间等于结束时间的条件并调用timer.cancel()

It may not be the time problem.. 可能不是时间问题。

If comparing two Strings, you'd better use equals() 如果比较两个字符串,则最好使用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. 如果要检查毫秒,只需将结束日期转换为millis date.getTime()并减去System.currentTimeMillis()-如果结果为0,则与毫秒相同。 If the difference is less than 1000 (1 * 1000) it is within the second. 如果差异小于1000(1 * 1000),则在第二个以内。 If it is less than 60000 (1 * 60 * 1000) it is within the minute. 如果小于60000(1 * 60 * 1000),则在分钟之内。

May be, you just don't know how to get the endTime . 可能是,您只是不知道如何获取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 尝试,祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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