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?

5
  • 2
    Convert them to an actual time-based representation and compare them instead. Commented Sep 21, 2014 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. Commented Sep 21, 2014 at 20:54
  • See my answer for a working example. Commented Sep 22, 2014 at 1: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. Commented Jul 29, 2019 at 18:01
  • 1
    @user1445967 Agreed. I re-opened the Question. And provided an Answer using java.time. Thanks. Commented Oct 8, 2019 at 6:15

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

FYI, the terribly troublesome date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later.
FYI before() method returns a boolean
16

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.

2 Comments

is there a way to compare string of different length, say start = "2019", end = "2020-02"?
@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.
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();
        }

    }

}

3 Comments

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 - Thanks for pointing the error. I appreciate it. I have fixed it now. Can you please undo the downvote ? Thanks.
FYI, the terribly troublesome date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later.
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));

Comments

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.

Comments

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

2 Comments

FYI: The Joda-Time project is now in maintenance mode, its creator, Stephen Colebourne, having gone on to lead JSR 310 defining the java.time classes built into Java 8+. See Tutorial by Oracle.
Java8 date api sucks. I am still using Joda with no problems.
0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.