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


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


Java方法中ChronoZonedDateTime接口的compareTo()方法將此日期與另一個日期進行比較。

用法

default int compareTo(ChronoZonedDateTime other)

參數:此方法接受參數other,該參數指定要與之比較的其他日期,並且不專門為null。


返回值:返回比較器值,如果比較器值較小,則為負;如果比較大,則為正。

以下程序說明了Java中ChronoZonedDateTime的compareTo()方法:

程序1

// Program to illustrate the compareTo() method 
  
import java.util.*; 
import java.time.*; 
import java.time.chrono.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
        // First date 
        ChronoZonedDateTime dt 
            = ZonedDateTime.parse( 
                "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); 
  
        System.out.println(dt); 
  
        // Second date 
        ChronoZonedDateTime dt1 
            = ZonedDateTime.parse( 
                "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); 
  
        System.out.println(dt1); 
  
        try { 
            // Compare both dates 
            System.out.println(dt1.compareTo(dt)); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}

輸出:

2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
0

程序2

// Program to illustrate the compareTo() method 
  
import java.util.*; 
import java.time.*; 
import java.time.chrono.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
        // First date 
        ChronoZonedDateTime dt 
            = ZonedDateTime.parse( 
                "2018-10-25T23:12:31.123+02:00[Europe/Paris]"); 
  
        System.out.println(dt); 
  
        // Second date 
        ChronoZonedDateTime dt1 
            = ZonedDateTime.parse( 
                "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); 
  
        System.out.println(dt1); 
  
        try { 
            // Compare both dates 
            System.out.println(dt1.compareTo(dt)); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}

輸出:

2018-10-25T23:12:31.123+02:00[Europe/Paris]
2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
1

參考: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoZonedDateTime.html#compareTo-java.time.chrono.ChronoZonedDateTime-



相關用法


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