Java中的OffsetTime類的compareTo()方法將此時間與另一個時間進行比較,如果它們相等,則返回零,或者根據比較結果返回正整數或負整數。
用法:
public int compareTo(OffsetTime other)
參數:此方法接受單個強製性參數other,該參數指定將與之進行比較的其他時間。
返回值:它返回比較器值。如果另一個日期較小,則返回負值;如果較大,則返回正值。
異常注意:如果傳遞的其他日期為null,則該函數將引發NullPointerException。
以下示例程序旨在說明compareTo()方法:
示例1:
// Java program to demonstrate the compareTo() method
import java.time.OffsetTime;
public class GFG {
public static void main(String[] args)
{
// Parses the time
OffsetTime time1
= OffsetTime.parse("15:30:30+07:00");
// Parses the time
OffsetTime time2
= OffsetTime.parse("15:30:30+07:00");
// gets the offset time1
System.out.println("time1: "
+ time1);
// gets the offset time2
System.out.println("time1: "
+ time2);
System.out.println("time1 when compared"
+ " to time2 returns: "
+ time1.compareTo(time2));
}
}
輸出:
time1: 15:30:30+07:00 time1: 15:30:30+07:00 time1 when compared to time2 returns: 0
程序2:
// Java program to demonstrate the compareTo() method
import java.time.OffsetTime;
public class GFG {
public static void main(String[] args)
{
// Parses the time
OffsetTime time1
= OffsetTime.parse("15:30:30+07:00");
// Parses the time
OffsetTime time2
= OffsetTime.parse("12:10:30+07:00");
// gets the offset time1
System.out.println("time1: "
+ time1);
// gets the offset time2
System.out.println("time1: "
+ time2);
System.out.println("time1 when compared"
+ " to time2 returns: "
+ time1.compareTo(time2));
}
}
輸出:
time1: 15:30:30+07:00 time1: 12:10:30+07:00 time1 when compared to time2 returns: 1
示例3::
// Java program to demonstrate the compareTo() method
import java.time.OffsetTime;
public class GFG {
public static void main(String[] args)
{
// Parses the time
OffsetTime time1
= OffsetTime.parse("15:30:30+07:00");
// Parses the time
OffsetTime time2
= OffsetTime.parse("17:10:30+07:00");
// gets the offset time1
System.out.println("time1: "
+ time1);
// gets the offset time2
System.out.println("time1: "
+ time2);
System.out.println("time1 when compared"
+ " to time2 returns: "
+ time1.compareTo(time2));
}
}
輸出:
time1: 15:30:30+07:00 time1: 17:10:30+07:00 time1 when compared to time2 returns: -1
參考: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetTime.html#compareTo-java.time.OffsetTime-
相關用法
- Java OffsetTime until()用法及代碼示例
- Java OffsetTime from()用法及代碼示例
- Java OffsetTime get()用法及代碼示例
- Java OffsetTime now()用法及代碼示例
- Java OffsetTime with()用法及代碼示例
- Java OffsetTime plus()用法及代碼示例
- Java OffsetTime isBefore()用法及代碼示例
- Java OffsetTime isAfter()用法及代碼示例
- Java OffsetTime query()用法及代碼示例
- Java OffsetTime format()用法及代碼示例
- Java OffsetTime minusNanos()用法及代碼示例
- Java OffsetTime minusMinutes()用法及代碼示例
- Java OffsetTime minusSeconds()用法及代碼示例
- Java OffsetTime equals()用法及代碼示例
- Java OffsetTime minusHours()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 OffsetTime compareTo() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。