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
相關用法
- Java OffsetDateTime from()用法及代碼示例
- Java OffsetDateTime with()用法及代碼示例
- Java OffsetDateTime get()用法及代碼示例
- Java OffsetDateTime until()用法及代碼示例
- Java OffsetDateTime minusSeconds()用法及代碼示例
- Java OffsetDateTime minusNanos()用法及代碼示例
- Java OffsetDateTime getDayOfYear()用法及代碼示例
- Java OffsetDateTime minusYears()用法及代碼示例
- Java OffsetDateTime plusDays()用法及代碼示例
- Java OffsetDateTime plusMonths()用法及代碼示例
- Java OffsetDateTime plusDays()用法及代碼示例
- Java OffsetDateTime plusSeconds()用法及代碼示例
- Java OffsetDateTime equals()用法及代碼示例
- Java OffsetDateTime minusHours()用法及代碼示例
- Java OffsetDateTime getDayOfWeek()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 OffsetDateTime compareTo() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。