Java中的 ChronoZonedDateTime compareTo() 方法和示例
Java方法中ChronoZonedDateTime接口的compareTo()方法将此日期与另一个日期进行比较。
语法:
default int compareTo(ChronoZonedDateTime other)
参数:此方法接受一个参数other ,该参数指定要比较的另一个日期,并且它不是专门为空的。
返回值:它返回比较器值,如果小于则返回负数,如果大于则返回正数。
下面的程序说明了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
方案二:
// 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-