📜  Java中的 LocalDateTime compareTo() 方法及示例

📅  最后修改于: 2022-05-13 01:54:25.528000             🧑  作者: Mango

Java中的 LocalDateTime compareTo() 方法及示例

Java中LocalDateTime 类compareTo()方法用于将此日期时间与作为参数传递的日期时间进行比较。

句法:

public int compareTo(ChronoLocalDateTime anotherDate)

参数:此方法接受参数anotherDate指定要比较的另一个日期时间。它不应该为空。

返回:该函数返回一个整数值,该整数值是比较后的比较器值。

下面的程序说明了 LocalDateTime.compareTo() 方法:

方案一:

// 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

方案二:

// 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: Java Java.time.chrono.ChronoLocalDateTime)