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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25963720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:36:02  来源:igfitidea点击:

How to compare two string dates in Java?

javastringdatecalendar

提问by john

I have two dates in String format like below -

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

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

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

I want to make sure startDate should be less than endDate. startDate should not be greater than endDate.

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

How can I compare these two dates and return boolean accordingly?

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

采纳答案by Makoto

Convert them to an actual Dateobject, then call before.

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

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

Recall that parsewill throw a ParseException, so you should either catch it in this code block, or declare it to be thrown as part of your method signature.

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

回答by AlexR

Use SimpleDateFormatto parse your string representation into instance of Date. The invoke getTime()to get milliseconds. Then compare the milliseconds.

用于SimpleDateFormat将您的字符串表示形式解析为Date. getTime()获取毫秒的调用。然后比较毫秒。

回答by Kenny Hung

The simplest and safest way would probably be to parse both of these strings as dates, and compare them. You can convert to a date using a SimpleDateFormat, use the before or after method on the date object to compare them.

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

回答by Jean Logeart

Use SimpleDateFormatto convert to Dateto compare:

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

回答by sid smith

Here is a fully working demo. For date formatting, refer - http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

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

    }

}

回答by Creditto

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));
        }
    }
}

OUTPUT

输出

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

回答by Atais

I think it could be done much simpler,

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

Using Joda Time

使用 Joda 时间

You can try parsing this dates simply:

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

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

回答by Basil Bourque

tl;dr

tl;博士

Use modern java.timeclasses to parse the inputs into LocalDateTimeobjects by defining a formatting pattern with DateTimeFormatter, and comparing by calling isBefore.

使用现代java.timeLocalDateTime通过使用 定义格式化模式DateTimeFormatter并通过调用 进行比较来将输入解析为对象isBefore

java.time

时间

The modern approach uses the java.timeclasses.

现代方法使用java.time类。

Define a formatting pattern to match your inputs.

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

Parse as LocalDateTimeobjects, as your inputs lack an indicator of time zone or offset-from-UTC.

解析为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 ) ;

Dump to console.

转储到控制台。

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

See this code run live at IdeOne.com.

查看此代码在 IdeOne.com 上实时运行

2014-09-12T00:00 is before 2014-09-13T00:00 = true

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

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

Java 中的日期时间类型表,包括现代的和传统的。



About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

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

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

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

Where to obtain the java.time classes?

从哪里获得 java.time 类?

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

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

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多