📜  Java中的日期after()方法

📅  最后修改于: 2022-05-13 01:55:35.459000             🧑  作者: Mango

Java中的日期after()方法

Java.util.Date.after()方法用于检查日期的当前实例是否在指定日期之后。

句法:

dateObject.after(Date specifiedDate)

参数:它只接受一个数据类型Date的参数specifiedDate 。这是与调用函数的日期实例相比要检查的日期。

返回值:此函数的返回类型为boolean 。如果日期的当前实例严格大于指定日期,则返回true 。否则返回false

异常:如果 specifiedDate 为 null,则调用此方法时将抛出NullPointerException

下面的程序说明了 Date 类中的 after() 方法:

方案一:

// Java code to demonstrate
// after() 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();
  
        // creating a date of object
        // storing the current date
        Date currentDate = new Date();
  
        System.out.print("Is currentDate after date one : ");
  
        // if currentDate is after dateOne
        System.out.println(currentDate.after(dateOne));
    }
}
输出:
Is currentDate after date one : true

方案二:演示Java.lang.NullPointerException

// Java code to demonstrate
// after() 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();
  
        // specifiedDate is assigned to null.
        Date specifiedDate = null;
  
        System.out.println("Passing null as parameter : ");
        try {
            // throws NullPointerException
            System.out.println(currentDate.after(specifiedDate));
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
输出:
Passing null as parameter : 
Exception: java.lang.NullPointerException