How do I know if a date is before another date?

This example demonstrate Date‘s class before() method to check if a date is earlier than another date.

package org.kodejava.example.util;

import java.util.Date;
import java.util.Calendar;

public class DateCompareBefore {
    public static void main(String[] args) {
        // Get current date
        Date today = new Date();

        // Subtract 1 day from the current date.
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Date yesterday = calendar.getTime();

        // Tests if this date is before the specified date. This method will
        // return true if the value time represented by the yesterday object
        // is earlier than today.
        if (yesterday.before(today)) {
            System.out.println(yesterday + " is before " + today);
        }
    }
}

The result of the code snippet above is:

Sat Oct 28 21:16:33 WITA 2017 is before Sun Oct 29 21:16:33 WITA 2017

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply