This example demonstrate Date
‘s class before()
method to check if a date is earlier than another date.
package org.kodejava.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:
Sun Oct 03 20:49:36 CST 2021 is before Mon Oct 04 20:49:36 CST 2021
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024