.before()
Published Jul 29, 2023
Contribute to Docs
The Date.before()
method checks whether a date occurs before another specified date, and returns a boolean value.
Syntax
firstDate.before(secondDate)
The Date.before()
takes only one parameter:
secondDate
: ADate
object to be compared chronologically with the first date.
It returns true
if the firstDate
is before the secondDate
and returns false
if the firstDate
is after the secondDate
. However, if a date value is null, it will raise a NullPointerException.
Example
The following example shows the implementation of Date.before()
:
import java.util.Date;public class Main {public static void main(String[] args) {Date firstDate = new Date(2023, 1, 18);Date secondDate = new Date(2023, 1, 19);Date thirdDate = null;System.out.println("Is firstDate before secondDate: " + firstDate.before(secondDate));System.out.println("Is secondDate before firstDate: " + secondDate.before(firstDate));System.out.println("Is thirdDate before firstDate:" + firstDate.before(thirdDate));}}
The output will be:
Is firstDate before secondDate: trueIs secondDate before firstDate: falseException in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "date" is nullat java.base/java.util.Date.getMillisOf(Date.java:957)at java.base/java.util.Date.before(Date.java:916)at Main.main(Main.java:12)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.