Skip to content
Related Articles

Related Articles

Compare Dates in Java

Improve Article
Save Article
  • Last Updated : 08 Jul, 2021
Improve Article
Save Article

The Date class represents a specific instant in time, with millisecond precision. The Date class of java.util package implements Serializable, Cloneable and Comparable interface. It provides constructors and methods to deal with date and time with java.
The following are the methods to compare dates in java
 

  1. Using Date.compareTo():
    Steps involved: 
    1. Create an object for SimpleDateFormat class initialising it with the format yyyy-mm-dd.
    2. Initialize the date variables using the above objects.
    3. Use compareTo() function of the date class for the comparisons of dates
    4. Print the result.
  2. Using Date.before(), Date.after() and Date.equals().
    This method is simpler than the first one.
    Steps involved: 
    1. Create an object for SimpleDateFormat class initialising it with the format yyyy-mm-dd.
    2. Initialize the date variables using the above objects.
    3. Use after() and before functions of the date class for the comparisons of dates
    4. Print the result.
  3. Using Calendar.before(), Calendar.after() and Calendar.equals().
    Steps involved: 
    1. Create an object for SimpleDateFormat class initialising it with the format yyyy-mm-dd.
    2. Initialize the date variables using the above objects.
    3. Initialize the Calendar class objects using the getinstance() functions.
    4. Using the setTime() function of calendar class assign the values to the calendar objects.
    5. Use after() and before functions of the Calendar class for the comparisons of dates
    6. Print the result.
  4. Using Java 8 isBefore(), isAfter(), isEqual() and compareTo() methods: In Java 8, the isBefore(), isAfter(), isEqual() and compareTo() are used to compare LocalDate, LocalTime and LocalDateTime.
    Steps involved: 
    1. Create objects of LocalDate class.
    2. Use the isAfter(), isBefore() and isEqual() functions of date class to compare the dates.
    3. Print the result.

 

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!