Date.before() method in Java checks if one date occurs before another specified date. It returns true if the calling date is earlier, and false otherwise. If the specified date is null, it throws a "NullPointerException". This method is useful for date comparisons, scheduling, and validations in Java programs.
Example:
import java.time.LocalDate;
public class DateBeforeExample {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2020, 1, 1);
LocalDate date2 = LocalDate.of(2021, 1, 1);
System.out.println("Is date1 before date2? " + date1.isBefore(date2));
}
}
Output
Is date1 before date2? true
Explanation:
- LocalDate.of(year, month, day) creates a date object with the given year, month, and day.
- isBefore() checks if the first date occurs before the second date.
Syntax
public boolean before(Date when)
- Parameters: "when" -> the date to compare with
- Return Value: It returns a Boolean value. It will return true if this date is before the specified date otherwise false.
Example 1: This code shows how to use Date.before() in Java to check if one date comes before another.
import java.util.Date;
import java.util.Calendar;
public class GfG {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 5);
c.set(Calendar.YEAR, 1996);
Date dateOne = c.getTime();
System.out.println("Date 1: " + dateOne);
Date currentDate = new Date();
System.out.println("Date 2: " + currentDate);
System.out.println("Is Date 2 before Date 1: " + currentDate.before(dateOne));
}
}
Output
Date 1: Thu Dec 05 07:01:14 UTC 1996 Date 2: Fri Dec 26 07:01:14 UTC 2025 Is Date 2 before Date 1: false
Explanation :
- Calendar.getInstance() creates a calendar object to set a custom date.
- c.set(...) sets the month, day, and year. Note: Months are 0-based (0 = January, 11 = December).
- c.getTime() converts the calendar to a Date object (dateOne).
- new Date() creates the current date (currentDate).
- currentDate.before(dateOne) checks if currentDate occurs before dateOne. Returns true if it does, otherwise false
Example 2: This code demonstrates what happens when Date.before() is called with a null date. It shows how a NullPointerException is handled in Java.
import java.util.Date;
public class GfG {
public static void main(String[] args)
{
Date currentDate = new Date();
System.out.println("Date 1: " + currentDate);
Date specifiedDate = null;
System.out.println("Date 1: " + specifiedDate);
System.out.println("On checking these 2 dates: ");
try {
System.out.println(currentDate.before(specifiedDate));
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Output
Date 1: Wed Jan 02 08:15:06 UTC 2019 Date 1: null On checking these 2 dates: Exception: java.lang.NullPointerException
Explanation: Calling currentDate.before(specifiedDate) throws a NullPointerException.