Java Date类的before()方法测试日期是否在指定的日期之前。
用法:
public boolean before(Date when)
参数:该函数接受一个参数,该参数指定必须检查的日期。
返回值:它返回一个布尔值。如果此日期早于指定日期,它将返回true,否则返回false。
异常:如果when为null,该函数将引发单个异常,该异常为NullPointerException。
下面的程序演示了上述函数:
// Java code to demonstrate
// before() function of Date class
import java.util.Date;
import java.util.Calendar;
public class GfG {
// main method
public static void main(String[] args)
{
// creating a Calendar object
Calendar c = Calendar.getInstance();
// set Month
// MONTH starts with 0 i.e. ( 0 - Jan)
c.set(Calendar.MONTH, 11);
// set Date
c.set(Calendar.DATE, 05);
// set Year
c.set(Calendar.YEAR, 1996);
// creating a date object with specified time.
Date dateOne = c.getTime();
System.out.println("Date 1: " + dateOne);
// creating a date of object
// storing the current date
Date currentDate = new Date();
System.out.println("Date 2: " + currentDate);
System.out.println("Is Date 2 before Date 1: "
+ currentDate.before(dateOne));
}
}
输出:
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
// Java code to demonstrate
// before() function of Date class
import java.util.Date;
public class GfG {
// main method
public static void main(String[] args)
{
// creating a date of object
// storing the current date
Date currentDate = new Date();
System.out.println("Date 1: " + currentDate);
// specifiedDate is assigned to null.
Date specifiedDate = null;
System.out.println("Date 1: " + specifiedDate);
System.out.println("On checking these 2 dates: ");
try {
// throws NullPointerException
System.out.println(currentDate
.before(specifiedDate));
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Date 1: Wed Jan 02 08:15:06 UTC 2019 Date 1: null On checking these 2 dates: Exception: java.lang.NullPointerException
相关用法
- Java Date from()用法及代码示例
- Java Date hashCode()用法及代码示例
- Java Date toString()用法及代码示例
- Java Date equals()用法及代码示例
- Java Date compareTo()用法及代码示例
- Java Date getTime()用法及代码示例
- Java Date clone()用法及代码示例
- Java Date setTime()用法及代码示例
- Java Date toInstant()用法及代码示例
- Java Date after()用法及代码示例
- Java HijrahChronology date()方法用法及代码示例
- Java HijrahChronology date()函数用法及代码示例
- Java DateFormat format(Date obj)用法及代码示例
注:本文由纯净天空筛选整理自Twinkl Bajaj大神的英文原创作品 Date before() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。