How do I compare two dates?

In this example you’ll see the utilization of SimpleDateFormat class for comparing two dates for equality. We convert the date object into string using the DateFormat instance and then compare it using String.equals() method.

package org.kodejava.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ComparingDate {
    public static void main(String[] args) {
        // Create a SimpleDateFormat instance with dd/MM/yyyy format
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

        // Get the current date
        Date today = new Date();

        // Create an instance of calendar that represents a new year date
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, 1);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.YEAR, 2021);

        String newYear = df.format(calendar.getTime());
        String now = df.format(today);

        // Using the string equals method we can compare the date.
        if (now.equals(newYear)) {
            System.out.println("Happy New Year!");
        } else {
            System.out.println("Have a nice day!");
        }
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.