我有两个 String
变量:
time22
将存储 Linux 命令生成的时间timeInTheList
将存储来 self 的ArrayList
的时间
time22
将获取最新时间,而 timeInTheList
将存储之前的一些时间。
我想比较这两次是否超过 30 分钟,但我无法实现。
我发现打印出一些关于日期、时间和年份的奇怪数据,我只需要时间,不需要任何日期或年份。
代码:
for(int x = 1;x<list1.size();x+=3)
{
try{
System.out.println("The time grab by linux command :"+time22);
String timeInTheList = list1.get(x);
System.out.println("The time in the balcklist.txt :" +timeInTheList);
SimpleDateFormat dateFormat1 = new SimpleDateFormat("HH:MM:SS");
Date Ftime1 = dateFormat1.parse(timeInTheList);
Date Stime2 = dateFormat1.parse(time22);
System.out.println("The Ftime1 value is :" +Ftime1);
System.out.println("The Stime2 value is :" +Stime2);
long diff1 = Stime2.getTime() - Ftime1.getTime();
System.out.println(Stime2.getTime());
System.out.println(Ftime1.getTime());
System.out.println("Difference between two time is :"+diff1);
if(diff1 > 1800)
{
System.out.println("it is more than 30 minute in the list");
String DeletedRule = list1.get(x+1).toString();
FinalDeletion(DeletedRule);
}
else
{
System.out.println("Keep in the list first,still not reach 30 minute");
}
}
catch(ParseException e)
{
e.printStackTrace();
}
}
这是我程序的输出:
Time from linux command(In TimeIsNow Method) :22:02:50
The time grab by linux command :22:02:50
The time in the balcklist.txt :21:19:46
The Ftime1 value is :Thu Jul 01 21:00:00 MYT 1971
The Stime2 value is :Sun Feb 01 22:00:00 MYT 1970
2730600050
47223000046
Difference between two time is :-44492399996
Keep in the list first,still not reach 30 minute
最佳答案
如果您使用的是 Java 8,则可以使用新日期/时间 API。 请尝试以下代码:
// Required imports
import java.time.LocalTime;
import java.time.Duration;
// Taken hard-coded values for testing purpose
String time22 = "22:02:50", timeInTheList = "21:19:46";
LocalTime Stime2 = LocalTime.parse(time22);
LocalTime Ftime1 = LocalTime.parse(timeInTheList);
System.out.println("Stime2: " + Stime2);
System.out.println("Ftime1: " + Ftime1);
Duration duration = Duration.between(Ftime1, Stime2);
long diff1 = duration.getSeconds();
System.out.println("duration: " + diff1);
if(diff1 > 1800){
System.out.println("it is more than 30 minute in the list");
/**
* Your remaining code goes here.
*/
}else{
System.out.println("Keep in the list first, still not reach 30 minute");
}
关于java - 无法比较时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44547178/