在 Java 中比较时间值的不同方法是什么?


LocalTime 类表示本地时间,即没有时区的时间。该类提供各种方法(如 isBefore()、isAfter() 和 isEqual())来比较两个时间。

示例

实时演示

import java.time.LocalTime;
public class Test {
   public static void main(String args[]) {  
      LocalTime Time1 = LocalTime.of(10, 15, 45);
      LocalTime Time2 = LocalTime.of(07, 25, 55);      
      Boolean bool1 = Time1.isAfter(Time2);  
      Boolean bool2 = Time1.isBefore(Time2);
      if(bool1){
         System.out.println(Time1+" is after "+Time2);
      }else if(bool2){
         System.out.println(Time1+" is before "+Time2);
      }else{
          System.out.println(Time1+" is equal to "+Time2);
      }
   }
}

输出

10:15:45 is after 07:25:55

示例

实时演示

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CreateDateTime {
   public static void main(String args[])throws ParseException{  
      String timeStr1 = "8:27:45 AM";
      String timeStr2 = "2:30:12 PM";
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:SS a");      
      Date dateTime1 = formatter.parse(timeStr1);      
      Date dateTime2 = formatter.parse(timeStr2);      
      Boolean bool1 = dateTime1.after(dateTime2);  
      Boolean bool2 = dateTime1.before(dateTime2);
      Boolean bool3 = dateTime1.equals(dateTime2);
      if(bool1){
         System.out.println(timeStr1+" is after "+timeStr2);
      }else if(bool2){
         System.out.println(timeStr1+" is before "+timeStr2);
      }else if(bool3){
         System.out.println(timeStr1+" is equla to "+timeStr2);
      }
   }
}

输出

8:27:45 AM is after 2:30:12 PM

更新于:2021 年 2 月 6 日

2K+ 浏览量

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.