How to Compare Dates in Java


In this example we will show the method to compare dates in Java.

Source Code

package com.beginner.examples;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareExample1 {

    public static void main(String[] args) throws ParseException {

         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Date date1 = df.parse("2017-07-01 00:00:00");
         Date date2 = df.parse("2020-06-15 09:29:30");

         if (date1.compareTo(date2)  0) {
             System.out.println("Date1 is after date2.");
         }
    }
}

Output:

Date1 is before date2.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments