Java .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: ADateobject 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.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours