.before()

ChiragAgg5k10 total contributions
Published Aug 20, 2023
Contribute to Docs
The .before()
method of the Calendar
class is used to check if one Calendar
instance is before another.
Syntax
myCalendar.before(otherCalendar)
Returns true
if the time given by myCalendar
is before the time given by otherCalendar
, false
otherwise.
Note: The
.before()
method returnsfalse
if the twoCalendar
instances represent the same time.
Example
In the example below, two Calendar
instances are created. The first represents the current date and time, the second represents the current date and time plus two hours. The .before()
method is used to check if the myCalendar
object is before the otherCalendar
object. The method is also used to check if the myCalendar
object is before itself.
import java.util.Calendar;public class Main {public static void main(String[] args) {// Create a Calendar instance representing the current date and timeCalendar myCalendar = Calendar.getInstance();// Create another Calendar instance representing the current date and time plus two hoursCalendar otherCalendar = Calendar.getInstance();otherCalendar.add(Calendar.HOUR_OF_DAY, 2);// Check if calendar is before otherCalendarif (myCalendar.before(otherCalendar)) {System.out.println("myCalendar is before otherCalendar");} else {System.out.println("myCalendar is not before otherCalendar");}// Check if calendar is before itselfif(myCalendar.before(myCalendar)) {System.out.println("myCalendar is before itself");} else {System.out.println("myCalendar is not before itself");}}}
Output for the above code will be:
myCalendar is before otherCalendarmyCalendar is not before itself
Looking to contribute?
- 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.