Date before() method in Java with Examples
Last Updated :
02 Jan, 2019
The before() method of Java Date class tests whether the date is before the specified date or not.
Syntax:
public boolean before(Date when)
Parameters: The function accepts a single parameter when which specifies the date that has to be checked.
Return Value: It returns a Boolean value. It will return true if this date is before the specified date otherwise false.
Exception: The function throws a single exception that is NullPointerException if when is null.
Program below demonstrates the above mentioned function:
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, 05 );
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 08:15:01 UTC 1996
Date 2: Wed Jan 02 08:15:01 UTC 2019
Is Date 2 before Date 1: false
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...