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


Java OffsetDateTime compareTo()用法及代码示例

Java中OffsetDateTime类的compareTo()方法将此日期时间与另一个日期时间进行比较。

用法:

public int compareTo(OffsetDateTime other)

参数:此方法接受单个参数other,该参数指定要比较的其他日期时间,而不是null。


返回值:它返回比较器值,如果小于则返回负值,如果大于则返回正值。

以下示例程序旨在说明compareTo()方法:

示例1:

// Java program to demonstrate the compareTo() method 
  
import java.time.OffsetDateTime; 
import java.time.ZonedDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Parses the date1 
        OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); 
  
        // Parses the date2 
        OffsetDateTime date2 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); 
  
        // Prints both dates 
        System.out.println("Date1: " + date1); 
        System.out.println("Date2: " + date2); 
  
        // Compare both 
        System.out.println("On coparing we get " + date1.compareTo(date2)); 
    } 
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date2: 2018-12-12T13:30:30+05:00
On coparing we get 0

程序2

// Java program to demonstrate the compareTo() method 
import java.time.OffsetDateTime; 
import java.time.ZonedDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Parses the date1 
        OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); 
  
        // Parses the date2 
        OffsetDateTime date2 = OffsetDateTime.parse("2015-12-12T13:30:30+05:00"); 
  
        // Prints both dates 
        System.out.println("Date1: " + date1); 
        System.out.println("Date2: " + date2); 
  
        // Compare both 
        System.out.println("On coparing we get " + date1.compareTo(date2)); 
    } 
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date2: 2015-12-12T13:30:30+05:00
On coparing we get 3

程序3

// Java program to demonstrate the compareTo() method 
import java.time.OffsetDateTime; 
import java.time.ZonedDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Parses the date1 
        OffsetDateTime date1 = OffsetDateTime.parse("2013-12-12T13:30:30+05:00"); 
  
        // Parses the date2 
        OffsetDateTime date2 = OffsetDateTime.parse("2015-12-12T13:30:30+05:00"); 
  
        // Prints both dates 
        System.out.println("Date1: " + date1); 
        System.out.println("Date2: " + date2); 
  
        // Compare both 
        System.out.println("On coparing we get " + date1.compareTo(date2)); 
    } 
}
输出:
Date1: 2013-12-12T13:30:30+05:00
Date2: 2015-12-12T13:30:30+05:00
On coparing we get -2

参考: https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjuster.html



相关用法

注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 OffsetDateTime compareTo() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。