30

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.

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

john
  • 11,311
  • 40
  • 131
  • 251
  • 2
    Convert them to an actual time-based representation and compare them instead. – Makoto Sep 21 '14 at 20:52
  • 3
    With that particular date format, you don't need to parse the dates because the fields are already in most-to-least-significant order, but @Makoto has the right idea in general. Plus, parsing the date will be robust against bad inputs. – Jeffrey Bosboom Sep 21 '14 at 20:54
  • See my answer for a working example. – sid smith Sep 22 '14 at 01:11
  • 2
    I don't believe the marked duplicate is the same question, the link points to a higher-level question about technique/strategy and advantages/disadvantages. This question asks for a code example of how to do it. – user1445967 Jul 29 '19 at 18:01
  • 1
    @user1445967 Agreed. I re-opened the Question. And provided [an Answer](https://stackoverflow.com/a/58281016/642706) using *java.time*. Thanks. – Basil Bourque Oct 08 '19 at 06:15

8 Answers8

52

Convert them to an actual Date object, then call before.

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

Recall that parse will 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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • Thanks. It helps me a lot. – Phoenix Sep 04 '15 at 05:44
  • 1
    FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/tutorial/datetime/TOC.html) classes built into Java 8 and later. – Basil Bourque Oct 02 '19 at 18:24
  • FYI before() method returns a boolean – Dushan Nov 26 '21 at 14:50
15

tl;dr

Use modern java.time classes to parse the inputs into LocalDateTime objects by defining a formatting pattern with DateTimeFormatter, and comparing by calling isBefore.

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your inputs.

Parse as LocalDateTime objects, as your inputs lack an indicator of time zone or offset-from-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.

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

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


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as 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.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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

Where to obtain the java.time classes?

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

The ThreeTen-Extra project 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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • is there a way to compare string of different length, say start = "2019", end = "2020-02"? – larueroad Apr 20 '20 at 16:05
  • @RayZ Yes. See the `Year` and `YearMonth` classes. For a year only, use January to get a year-month. I suggest you post your own Question on that. And answer it yourself if you figure it out. – Basil Bourque Apr 20 '20 at 20:26
11

Here is a fully working demo. For date formatting, refer - 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();
        }

    }

}
sid smith
  • 533
  • 1
  • 6
  • 18
  • Your time format is wrong. The `Y` I could forgive (but it won't be compatible with calendars that don't support week years), but the `DD` is outright incorrect. – Makoto Sep 21 '14 at 21:21
  • @Makoto - Thanks for pointing the error. I appreciate it. I have fixed it now. Can you please undo the downvote ? Thanks. – sid smith Sep 22 '14 at 01:06
  • FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/tutorial/datetime/TOC.html) classes built into Java 8 and later. – Basil Bourque Oct 08 '19 at 06:06
4

Use SimpleDateFormat to convert to Date to compare:

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));
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
2

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.

Kenny Hung
  • 442
  • 3
  • 10
2

I think it could be done much simpler,

Using Joda Time

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));
Atais
  • 10,857
  • 6
  • 71
  • 111
  • FYI: The [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), its creator, [Stephen Colebourne](https://stackoverflow.com/users/38896/jodastephen), having gone on to lead [JSR 310](https://jcp.org/en/jsr/detail?id=310) defining the [*java.time*](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html) classes built into Java 8+. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 08 '19 at 06:07
  • Java8 date api sucks. I am still using Joda with no problems. – Atais Oct 08 '19 at 07:06
0

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

AlexR
  • 114,158
  • 16
  • 130
  • 208
0
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
TiiJ7
  • 3,332
  • 5
  • 25
  • 37
Thadeuse
  • 1,713
  • 2
  • 12
  • 19