【问题标题】:Fail to compare time ranges无法比较时间范围
【发布时间】:2017-06-14 14:08:56
【问题描述】:

我有两个String 变量:

  • time22会存储Linux命令生成的时间
  • timeInTheList 将存储我的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

【问题讨论】:

  • 你用 jodatime 标签标记了这个问题,但你的代码没有使用它。您是否正在使用(或想要使用)Joda-Time?
  • 我有 joda-time 库,但我不确定如何在这种情况下使用它。我将它用于其他目的
  • @yumi 将此类澄清发布为对您的问题的编辑而不是评论。

标签: java time jodatime date-comparison


【解决方案1】:

如果您使用的是 Java 8,则可以使用 New Date/Time 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");
}

【讨论】:

  • 你也可以用duration.toMinutes()代替getSeconds()
  • 是的,当然。但是问题中yumi贴的代码中,有秒的比较,所以我用了getSeconds()方法。
【解决方案2】:

在 Joda-Time 中,您可以使用 DateTimeFormatter 解析输入 String 并创建 LocalTime 对象 - LocalTime 似乎是最佳选择,因为您只处理时间(小时/分/秒)并且不需要知道日期(日/月/年)。

拥有LocalTime 对象,您可以使用Minutes 类来获取它们之间的分钟数:

import org.joda.time.LocalTime;
import org.joda.time.Minutes;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

String time22 = "22:02:50";
String timeInTheList = "21:19:46";

// create formatter with format hour:minute:second
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");

// parse Strings
LocalTime sTime2 = fmt.parseLocalTime(time22);
LocalTime fTime1 = fmt.parseLocalTime(timeInTheList);

// get the minutes between them
int minutes = Minutes.minutesBetween(fTime1, sTime2).getMinutes();
System.out.println(minutes); // 43

上面的代码会输出4321:19:4622:02:50之间的分钟数)。

由于输入位于 standard ISO-8601 format (HH:mm:ss) 中,因此您也可以在不使用格式化程序的情况下解析它们:

LocalTime sTime2 = LocalTime.parse(time22);
LocalTime fTime1 = LocalTime.parse(timeInTheList);

Java 新的日期/时间 API

Joda-Time 已停用并被新的 API 取代,因此我不建议使用 joda 启动新项目。即使在joda's website 中,它也说:“请注意,Joda-Time 被认为是一个基本上“完成”的项目。没有计划进行重大改进。如果使用 Java SE 8,请迁移到 java.time (JSR-310 )。”

因此,如果您在 Joda-Time 中没有庞大的代码库(这需要大量工作才能迁移),或者如果您想使用新的 API,请在下面查看如何使用它。

旧的类(DateCalendarSimpleDateFormat)有 lots of problems,它们正在被新的 API 取代。

如果您使用的是 Java 8,请考虑使用 new java.time API。更简单,less bugged and less error-prone than the old APIs

如果您使用的是 Java ,则可以使用 ThreeTen Backport,这是 Java 8 新日期/时间类的一个很好的向后移植。对于Android,还有ThreeTenABP(更多关于如何使用它here)。

下面的代码适用于两者。 唯一的区别是包名(在 Java 8 中是 java.time,在 ThreeTen Backport(或 Android 的 ThreeTenABP)中是 org.threeten.bp),但类和方法 names 是相同的。

代码和Joda的很相似:

// if you're using ThreeTen Backport, replace java.time by org.threeten.bp
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

String time22 = "22:02:50";
String timeInTheList = "21:19:46";

// parse Strings
LocalTime sTime2 = LocalTime.parse(time22);
LocalTime fTime1 = LocalTime.parse(timeInTheList);

// get the minutes between them
long minutes = ChronoUnit.MINUTES.between(fTime1, sTime2);
System.out.println(minutes); // 43

输出相同(43 分钟)。


注意事项:

在您的原始代码中,有两个问题:

  • 格式错误:MM 是月份,SS 是秒的小数部分(查看SimpleDateFormat javadoc 了解更多详情)。这就是为什么你在解析时会得到意想不到的结果:
    • 解析22:02:50时,将02作为月份(所以变成二月)。所有缺少的字段都设置为默认值(日为 1,年为 1970,分钟为 0,依此类推)
    • 解析21:19:46时,将19作为月份。因此解析器采用年份 (1970) 的默认值并从中获取第 19th 个月(考虑到 1970 年 1 月是第一个月,第 19th 个月是1971 年 7 月)
  • getTime() 方法返回自 January 1, 1970, 00:00:00 GMT 以来的毫秒数,因此您可以得到毫秒之间的差异(您需要将其转换为分钟)。

无论如何,使用 Joda-Time(或新的 Date/Time API)会使事情变得更容易,我不建议使用旧的 SimpleDateFormat 类。

【讨论】:

  • 一切正常,为你加油,让我学习新东西
  • Java 8 方法有效,但 joda-time 与其他库有一些兼容问题,因为我使用的是 java 8,所以我只使用 java 8 方法
  • @yumi 好!更好地使用新的 API!编码愉快!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多