当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。