how to check if one date is after another in java?

10,456

Solution 1

try {
    System.out.println("Enter first date : (dd/MM/yyyy)");
    BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date date1 = sdf.parse(bufferRead.readLine());
    System.out.println("Enter second date : (dd/MM/yyyy)");
    Date date2 = sdf.parse(bufferRead.readLine());
    System.out.println(date1 + "\n" + date2);
    if (date1.after(date2)) {
        System.out.println("Date1 is after Date2");
    } else {
            System.out.println("Date2 is after Date1");
    }
} catch (IOException e) {
    e.printStackTrace();
}

Solution 2

To compare two dates :

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");

            Date firstDate = sdf.parse("01/01/2014");
            Date secondDate = sdf.parse("15/03/2014");

            if(firstDate.before(secondDate)){
                System.out.println("firstDate <  secondDate");
            }
            else if(firstDate.after(secondDate)){
                System.out.println("firstDate >  secondDate");
            }
            else if(firstDate.equals(secondDate)){
                System.out.println("firstDate = secondDate");
            }

Solution 3

tl;dr

LocalDate ld1 = LocalDate.parse( "01/01/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld2 = LocalDate.parse( "15/03/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld3 = LocalDate.of( 2014 , Month.JULY , 1 ) ;

Boolean isFirstDateBeforeSecondDate = ld1.isBefore( ld2 ) ;
Boolean isThirdDateBeforeSecondDate = ld3.isBefore( ld2 ) ;

Boolean result = ( isFirstDateBeforeSecondDate && isThirdDateBeforeSecondDate ) ;

return result ;

Using java.time

The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).

The LocalDate class represents a date-only value without time-of-day and without time zone.

Define a formatting pattern to match your input strings using the DateTimeFormatter class.

String input = "15/03/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( input , f );

ld.toString(): 2014-03-15

To specify a fixed date, pass year, month, and dayOfMonth. For the month, you may specify a number, sanely numbered 1-12 for January-December (unlike the crazy 0-11 in the legacy classes!). Or you may choose to use the Month enum objects.

LocalDate firstOf2014 = LocalDate.of( 2014 , Month.JANUARY , 1 );

Compare using isBefore, isEqual, or isAfter methods.

Boolean isInputDateBeforeFixedDate = ld.isBefore( firstOf2014 ) ;

isInputDateBeforeFixedDate.toString(): false

ISO 8601

If possible, replace your particular date string format with the standard ISO 8601 format. That standard defines many useful practical unambiguous string formats for date-time values.

The java.time classes use the standard formats by default when parsing/generating strings. You can see examples in the code above. For a date-only value, the standard format is YYYY-MM-DD.


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.

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

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

Where to obtain the java.time classes?

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.

Solution 4

Use SimpleDateFormat to convert a string to Date.

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("01/01/2017");

Date has before and after methods and can be compared to each other as follows:

if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
    // In between
}

For an inclusive comparison:

if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
    /* historyDate <= todayDate <= futureDate */ 
}
Share:
10,456
user3087192
Author by

user3087192

Updated on June 04, 2022

Comments

  • user3087192
    user3087192 about 2 years

    I am taking in two dates as command line arguments and want to check if the first one is after the second date. the format of the date it "dd/MM/yyy". Example: java dateCheck 01/01/2014 15/03/2014 also i will need to check if a third date hardcoded into the program is before the second date.

  • Basil Bourque
    Basil Bourque about 7 years
    (a) Your formatting pattern does not suit your example data. Three 'y' characters instead of four, and a SLASH instead of a FULL STOP. (b) FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.