什么是比较Date之前更好的方法before()或isBefore()

时间:2017-02-13 10:30:06

标签: java date java-8

我正在通过双向(旧的和新的)比较两个日期

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}

输出:

  public static void main(String[] args) throws ParseException {
    // TODO Auto-generated method stub
     long  startTime1= Calendar.getInstance().getTimeInMillis();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
     Date date1 = sdf.parse("2009-12-31");
     Date date2 = sdf.parse("2010-01-31");
     if(date1.before(date2)){
         System.out.println("date1 is before d2");
     }
     long  endTime1= Calendar.getInstance().getTimeInMillis();
     long totalTime1 =endTime1-startTime1;
     System.out.println(totalTime1);

     long  startTime2= Calendar.getInstance().getTimeInMillis();
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
     LocalDate localDate1 = LocalDate.parse("2009-12-31",formatter);
     LocalDate localDate2 = LocalDate.parse("2010-01-31",formatter);
     if(localDate1.isBefore(localDate2)){
         System.out.println("date1 is before d2");
     }
     long  endTime2= Calendar.getInstance().getTimeInMillis();
     long totalTime2 =endTime2-startTime2;
     System.out.println(totalTime2);


}

所以最好的方法是什么,因为 isBefore 花费更多时间然后 方法,但 isBefore 进入 java 8 < / strong>任何人都可以告诉我们什么时候使用isBefore?

我也检查了这个,但我想知道性能

Should I use java.util.Date or switch to java.time.LocalDate

2 个答案:

答案 0 :(得分:4)

使用新的。 LocalDateLocalTimeLocalDateTime都是不可变且线程安全的。它们使用起来更安全。

答案 1 :(得分:0)

ChronoUnit在比较日期时效率更高。 以下是您可以使用的示例:

    LocalDateTime timeNow = LocalDateTime.now();
    LocalDateTime timeAfterSometime = timeNow.plusHours(4).plusMinutes(11);

    System.out.println("timeNow = "+timeNow);
    System.out.println("timeAfterSometime = "+timeAfterSometime);

    long minutesDiff = ChronoUnit.MINUTES.between(timeNow, timeAfterSometime); // 251
    long hoursDiff = ChronoUnit.HOURS.between(timeNow, timeAfterSometime); // 4

    System.out.println("minutesDiff = "+minutesDiff);
    System.out.println("hoursDiff = "+hoursDiff);

输出如下:

  

timeNow = 2017-02-13T16:05:00.617   timeAfterSometime = 2017-02-13T20:16:00.617   minutesDiff = 251   hoursDiff = 4