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


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


Java Date類的compareTo()方法比較兩個日期並將它們排序。

用法:

public int compareTo(Date anotherDate)

參數:該函數接受單個參數anotherDate,該參數指定要比較的日期。


返回值:該函數提供以下指定的三個返回值:

  • 如果參數Date等於此Date,則返回值0。
  • 如果此Date在Date參數之前,則返回小於0的值。
  • 如果此Date在Date參數之後,則返回大於0的值。

異常:如果anotherDate為null,則該函數引發一個異常,該異常為NullPointerException。

下麵的程序演示了上述函數:

// Java code to demonstrate 
// compareTo() 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); 
  
        // compares 
        System.out.println("On Comparison: "
                           + currentDate 
                                 .compareTo(dateOne)); 
    } 
}
輸出:
Date 1: Thu Dec 05 08:17:55 UTC 1996
Date 2: Wed Jan 02 08:17:55 UTC 2019
On Comparison: 1
// Java code to demonstrate 
// compareTo() function of Date class 
  
import java.util.Date; 
  
public class GfG { 
    // main method 
    public static void main(String[] args) 
    { 
  
        // creating a date of object 
        // stospecified datent date 
        Date currentDate = new Date(); 
  
        System.out.println("Date 1: " + currentDate); 
  
        // specifiedDate is assigned to null. 
        Date specifiedDate = null; 
  
        System.out.println("Date 2: " + specifiedDate); 
  
        System.out.println("Passing null as parameter: "); 
        try { 
            // throws NullPointerException 
            System.out.println(currentDate 
                                   .compareTo(specifiedDate)); 
        } 
        catch (Exception e) { 
            System.out.println("Exception: " + e); 
        } 
    } 
}
輸出:
Date 1: Wed Jan 02 08:18:02 UTC 2019
Date 2: null
Passing null as parameter: 
Exception: java.lang.NullPointerException


相關用法


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