當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Date after()用法及代碼示例


java.util.Date.after()方法用於檢查日期的當前實例是否在指定的日期之後。

用法:

dateObject.after(Date specifiedDate)

參數:它僅采用一個參數類型為Date的數據類型Date。與調用該函數的日期實例相比,這是要檢查的日期。


返回值:該函數的返回類型為布爾值。如果日期的當前實例嚴格大於指定的日期,則返回true。否則,它返回false。

異常:如果指定的日期為null,則在調用此方法時將拋出NullPointerException。

下麵的程序說明Date類中的after()方法:

示例1:

// 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

示例2:演示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


相關用法


注:本文由純淨天空篩選整理自ShivamKD大神的英文原創作品 Date after() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。