【问题标题】:How to compare two string dates in Java?如何比较Java中的两个字符串日期?
【发布时间】:2014-11-15 19:23:00
【问题描述】:

我有两个字符串格式的日期,如下所示 -

String startDate = "2014/09/12 00:00";

String endDate = "2014/09/13 00:00";

我想确保 startDate 应该小于 endDate。 startDate 不应大于 endDate。

如何比较这两个日期并相应地返回布尔值?

【问题讨论】:

  • 将它们转换为实际的基于时间的表示,然后进行比较。
  • 使用这种特定的日期格式,您不需要解析日期,因为这些字段已经按照从高到低的顺序排列,但@Makoto 总体上是正确的。另外,解析日期对于错误的输入非常有效。
  • 查看我的答案以获取工作示例。
  • 我不相信标记的重复是同一个问题,链接指向一个关于技术/策略和优点/缺点的更高级别的问题。此问题要求提供如何执行此操作的代码示例。
  • @user1445967 同意。我重新打开了问题。并使用 java.time 提供an Answer。谢谢。

标签: java string date calendar


【解决方案1】:

我们需要首先将给定的字符串日期解析为日期对象以进一步比较。我们可以使用属于 java.util.Date 包的 SimpleDateFormat 类方法。可以使用 before、after 或 compareTo 等比较方法。

对于基本的日期计算,我们可以使用 java.util.Date 方法。如果我们关心时区,线程安全程序,它可以与新引入的 api java.time 一起使用。它引入了许多强大的功能和方法来克服旧日期 api 中的问题。

请使用 LocalDate 方法查找日期比较的代码块。示例代码如下

 String startDt = "2020-06-10";
    
    String endDt =  "2021-04-12";

    LocalDate dStart = LocalDate.parse(startDt);

    LocalDate dEnd = LocalDate.parse(endDt);

    if (dStart.isAfter(dEnd)) {
        //Start Date is greater than End Date Block

    } else if (dStart.isBefore(dEnd)) {

      // Start Date is less than End Date block

    } else {

        // Start Date is Equal to End Date
    }

找到date comparison的文章,可以查看更多详情。

【讨论】:

    【解决方案2】:
    public class DateComparision
    {
    
        public static void main(String args[]) throws AssertionError, ParseException
        {
    
            DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    
            //comparing date using compareTo method in Java
            System.out.println("Comparing two Date in Java using CompareTo method");
    
            compareDatesByCompareTo(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
            compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
            compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
    
            //comparing dates in java using Date.before, Date.after and Date.equals
            System.out.println("Comparing two Date in Java using Date's before, after and equals method");
    
            compareDatesByDateMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
            compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
            compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
    
            //comparing dates in java using Calendar.before(), Calendar.after and Calendar.equals()
    
            System.out.println("Comparing two Date in Java using Calendar's before, after and equals method");
            compareDatesByCalendarMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
            compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
            compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
    
        }
    
        public static void compareDatesByCompareTo(DateFormat df, Date oldDate, Date newDate)
        {
            //how to check if date1 is equal to date2
            if (oldDate.compareTo(newDate) == 0)
            {
                System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
            }
    
            //checking if date1 is less than date 2
            if (oldDate.compareTo(newDate) < 0)
            {
                System.out.println(df.format(oldDate) + " is less than " + df.format(newDate));
            }
    
            //how to check if date1 is greater than date2 in java
            if (oldDate.compareTo(newDate) > 0)
            {
                System.out.println(df.format(oldDate) + " is greater than " + df.format(newDate));
            }
        }
    
        public static void compareDatesByDateMethods(DateFormat df, Date oldDate, Date newDate)
        {
            //how to check if two dates are equals in java
            if (oldDate.equals(newDate))
            {
                System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
            }
    
            //checking if date1 comes before date2
            if (oldDate.before(newDate))
            {
                System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
            }
    
            //checking if date1 comes after date2
            if (oldDate.after(newDate))
            {
                System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
            }
        }
    
        public static void compareDatesByCalendarMethods(DateFormat df, Date oldDate, Date newDate)
        {
    
            //creating calendar instances for date comparision
            Calendar oldCal = Calendar.getInstance();
            Calendar newCal = Calendar.getInstance();
    
            oldCal.setTime(oldDate);
            newCal.setTime(newDate);
    
            //how to check if two dates are equals in java using Calendar
            if (oldCal.equals(newCal))
            {
                System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
            }
    
            //how to check if one date comes before another using Calendar
            if (oldCal.before(newCal))
            {
                System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
            }
    
            //how to check if one date comes after another using Calendar
            if (oldCal.after(newCal))
            {
                System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
            }
        }
    }
    

    输出

    Comparing two Date in Java using CompareTo method
    01-01-2012 and 01-01-2012 are equal to each other
    02-03-2012 is less than 04-05-2012
    02-03-2012 is greater than 01-02-2012
    
    Comparing two Date in Java using Date's before, after and equals method
    01-01-2012 and 01-01-2012 are equal to each other
    02-03-2012 comes before 04-05-2012
    02-03-2012 comes after 01-02-2012
    
    Comparing two Date in Java using Calendar's before, after and equals method
    01-01-2012 and 01-01-2012 are equal to each other
    02-03-2012 comes before 04-05-2012
    02-03-2012 comes after 01-02-2012
    

    【讨论】:

      【解决方案3】:

      tl;博士

      使用现代的java.time 类,通过使用DateTimeFormatter 定义格式模式并通过调用isBefore 进行比较,将输入解析为LocalDateTime 对象。

      java.time

      现代方法使用 java.time 类。

      定义格式模式以匹配您的输入。

      解析为 LocalDateTime 对象,因为您的输入缺少时区指示符或与 UTC 的偏移量。

      String startInput = "2014/09/12 00:00";
      String stopInput = "2014/09/13 00:00";
      
      DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/MM/dd HH:mm" );
      
      LocalDateTime start = LocalDateTime.parse( startInput , f ) ;
      LocalDateTime stop = LocalDateTime.parse( stopInput , f ) ;
      boolean isBefore = start.isBefore( stop ) ;
      

      转储到控制台。

      System.out.println( start + " is before " + stop + " = " + isBefore );
      

      看到这个code run live at IdeOne.com

      2014-09-12T00:00 早于 2014-09-13T00:00 = true


      关于java.time

      java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

      要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

      Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

      您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

      从哪里获得 java.time 类?

      ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

      【讨论】:

      • 有没有办法比较不同长度的字符串,比如 start = "2019", end = "2020-02"?
      • @RayZ 是的。请参阅 YearYearMonth 类。仅一年,使用一月来获得年月。我建议你在上面发布你自己的问题。如果你弄明白了,自己回答吧。
      【解决方案4】:

      使用SimpleDateFormat 转换为Date 进行比较:

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
      Date start = sdf.parse(startDate);
      Date end = sdf.parse(endDate);
      System.out.println(start.before(end));
      

      【讨论】:

        【解决方案5】:

        我认为它可以做得更简单,

        使用 Joda 时间

        您可以尝试简单地解析此日期:

        import org.joda.time.DateTime;
        import org.joda.time.format.DateTimeFormat;
        import org.joda.time.format.DateTimeFormatter;
        
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm");
        DateTime d1 = formatter.parseDateTime(startDate);
        DateTime d2 = formatter.parseDateTime(endDate);
        
        Assert.assertTrue(d1.isBefore(d2));
        Assert.assertTrue(d2.isAfter(d1));
        

        【讨论】:

        【解决方案6】:

        这是一个完整的演示。有关日期格式,请参阅 - http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

        import java.text.ParseException;
        import java.text.SimpleDateFormat;
        import java.util.Date;
        import java.util.Locale;
        
        public class Dating {
        
            public static void main(String[] args) {
        
                String startDate = "2014/09/12 00:00";
                String endDate = "2014/09/13 00:00";
        
                try {
                    Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
                            .parse(startDate);
                    Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
                            .parse(endDate);
        
                    System.out.println(start);
                    System.out.println(end);
        
                    if (start.compareTo(end) > 0) {
                        System.out.println("start is after end");
                    } else if (start.compareTo(end) < 0) {
                        System.out.println("start is before end");
                    } else if (start.compareTo(end) == 0) {
                        System.out.println("start is equal to end");
                    } else {
                        System.out.println("Something weird happened...");
                    }
        
                } catch (ParseException e) {
                    e.printStackTrace();
                }
        
            }
        
        }
        

        【讨论】:

        • 您的时间格式错误。 Y 我可以原谅(但它与不支持周年的日历不兼容),但 DD 完全不正确。
        • @Makoto - 感谢您指出错误。我很感激。我现在已经修好了。你能撤消否决票吗?谢谢。
        • 仅供参考,诸如 java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等非常麻烦的日期时间类现在是 legacy,被 Java 8 及更高版本中内置的 java.time 类所取代.
        【解决方案7】:

        最简单和最安全的方法可能是将这两个字符串都解析为日期,然后进行比较。您可以使用 SimpleDateFormat 转换为日期,使用日期对象的 before 或 after 方法来比较它们。

        【讨论】:

          【解决方案8】:

          使用SimpleDateFormat 将您的字符串表示解析为Date 的实例。调用 getTime() 以获取毫秒数。然后比较毫秒。

          【讨论】:

            【解决方案9】:

            将它们转换为实际的Date 对象,然后调用before

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
            System.out.println(sdf.parse(startDate).before(sdf.parse(endDate)));
            

            回想一下,parse 将抛出 ParseException,因此您应该在此代码块中捕获它,或者将其声明为方法签名的一部分。

            【讨论】:

            • 谢谢。这对我帮助很大。
            • 仅供参考,诸如 java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等非常麻烦的日期时间类现在是 legacy,被 Java 8 及更高版本中内置的 java.time 类所取代.
            • 仅供参考 before() 方法返回一个布尔值
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-31
            • 1970-01-01
            • 2013-01-24
            • 1970-01-01
            • 2013-12-20
            相关资源
            最近更新 更多