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


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


Java中的LocalDateTime類的compareTo()方法用於將此日期時間與作為參數傳遞的日期時間進行比較。

用法:

public int compareTo(ChronoLocalDateTime anotherDate)

參數:此方法接受參數anotherDate,該參數指定要與之進行比較的另一個日期時間。它不能為空。


返回值:該函數返回一個整數值,它是比較後的比較器值。

以下示例程序旨在說明LocalDateTime.compareTo()方法:

示例1:

// Program to illustrate the compareTo() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
        // Parses the date 
        LocalDateTime dt1 
            = LocalDateTime 
                  .parse("2018-11-03T12:45:30"); 
  
        // Prints the date 
        System.out.println("Date 1: " + dt1); 
  
        // Parses the date 
        LocalDateTime dt2 
            = LocalDateTime 
                  .parse("2015-01-05T12:45:30"); 
  
        // Prints the date 
        System.out.println("Date 2: " + dt2); 
  
        // Compares the date 
        System.out.println("After comparison: "
                           + dt2.compareTo(dt1)); 
    } 
}
輸出:
Date 1: 2018-11-03T12:45:30
Date 2: 2015-01-05T12:45:30
After comparison: -3

示例2:

// Program to illustrate the compareTo() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
        // Parses the date 
        LocalDateTime dt1 
            = LocalDateTime 
                  .parse("2010-12-05T12:50:30"); 
  
        // Prints the date 
        System.out.println("Date 1: " + dt1); 
  
        // Parses the date 
        LocalDateTime dt2 
            = LocalDateTime 
                  .parse("2012-05-10T12:50:30"); 
  
        // Prints the date 
        System.out.println("Date 2: " + dt2); 
  
        // Compares the date 
        System.out.println("After comparison: "
                           + dt2.compareTo(dt1)); 
    } 
}
輸出:
Date 1: 2010-12-05T12:50:30
Date 2: 2012-05-10T12:50:30
After comparison: 2

參考: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#compareTo(java.time.chrono.ChronoLocalDateTime)



相關用法


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