如何比较Java中的两个字符串日期?

时间:2014-09-21 20:50:24

标签: java string date calendar

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

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

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

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

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

8 个答案:

答案 0 :(得分:31)

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

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

回想一下parse会抛出一个ParseException,所以你应该在这个代码块中捕获它,或者声明它作为方法签名的一部分被抛出。

答案 1 :(得分:9)

这是一个完全有效的演示。有关日期格式的信息,请参阅 - 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();
        }

    }

}

答案 2 :(得分: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));

答案 3 :(得分:2)

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

答案 4 :(得分:2)

我认为可以做得更简单,

使用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));

答案 5 :(得分:2)

tl; dr

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

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 =真

Table of date-time types in Java, both modern and legacy.


关于 java.time

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

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

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

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

在哪里获取java.time类?

Table of which java.time library to use with which version of Java or Android.

ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

答案 6 :(得分:0)

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

答案 7 :(得分:0)

公共类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));
    }
}

}

输出: ......

使用CompareTo方法在Java中比较两个Date 01-01-2012和01-01-2012彼此相同 02-03-2012不到04-05-2012 02-03-2012大于01-02-2012

使用Date的before,after和equals方法比较Java中的两个Date 01-01-2012和01-01-2012彼此相同 02-03-2012在04-05-2012之前到来 02-03-2012来自2012年1月1日之后

使用Calendar的before,after和equals方法比较Java中的两个Date 01-01-2012和01-01-2012彼此相同 02-03-2012在04-05-2012之前到来 02-03-2012来自2012年1月1日之后