Java中的 ChronoLocalDateTime compareTo() 方法及示例
Java方法中ChronoLocalDateTime接口的compareTo()方法将此日期与另一个日期进行比较。
语法:
default int compareTo(ChronoLocalDateTime other)
参数:此方法接受一个参数other ,该参数指定要比较的另一个日期,并且它不是专门为空的。
返回值:它返回比较器值,如果小于则返回负数,如果大于则返回正数。
下面的程序说明了Java中 ChronoLocalDateTime 的 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
ChronoLocalDateTime dt
= LocalDateTime.parse("2018-12-06T19:21:12");
System.out.println(dt);
// Second date
ChronoLocalDateTime dt1
= LocalDateTime.parse("2018-12-06T19:21:12");
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
2018-12-06T19:21:12
0
方案二:
// 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
ChronoLocalDateTime dt
= LocalDateTime.parse("2018-12-05T19:21:12");
System.out.println(dt);
// Second date
ChronoLocalDateTime dt1
= LocalDateTime.parse("2018-12-06T19:21:12");
System.out.println(dt1);
try {
// Compare both dates
System.out.println(dt1.compareTo(dt));
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
2018-12-05T19:21:12
2018-12-06T19:21:12
1
参考:https://docs.oracle.com/javase/9/docs/api/ Java/time/chrono/ChronoLocalDateTime.html#compareTo-java.time.chrono.ChronoLocalDateTime-