Instant類的truncatedTo()方法用於以指定單位獲取此Instant的值。此方法采用參數Unit,即此Instant被截斷為的Unit。它返回帶有指定單位的值的截斷的不可變Instant。
用法:
public Instant truncatedTo(TemporalUnit unit)
參數:此方法采用參數uint,該參數uint是要將此Instant截斷的單位。它不能為空。
返回值:此方法以指定的單位返回不可變的截斷的Instant。
異常:此方法引發以下異常:
- DateTimeException:如果單位對於截斷無效。
- UnsupportedTemporalTypeException:如果不支持該設備。
以下示例程序旨在說明Instant.truncatedTo()方法:
程序1:
// Java program to demonstrate
// Instant.truncatedTo() method
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
// create a Instant object
Instant instant
= Instant.parse("2018-12-30T09:24:54.63Z");
// print instance
System.out.println("Instant before"
+ " truncate: "
+ instant);
// truncate to ChronoUnit.HOURS
// means unit smaller than Hour
// will be Zero
Instant returnvalue
= instant.truncatedTo(ChronoUnit.HOURS);
// print result
System.out.println("Instant after "
+ " truncate: "
+ returnvalue);
}
}
輸出:
Instant before truncate: 2018-12-30T09:24:54.630Z Instant after truncate: 2018-12-30T09:00:00Z
程序2:
// Java program to demonstrate
// Instant.truncatedTo() method
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
// create a Instant object
Instant instant
= Instant.parse("2018-12-30T09:24:54.63Z");
// print instance
System.out.println("Instant before"
+ " truncate: "
+ instant);
// truncate to ChronoUnit.DAYS
// means unit smaller than DAY
// will be Zero
Instant returnvalue
= instant.truncatedTo(ChronoUnit.DAYS);
// print result
System.out.println("Instant after "
+ " truncate: "
+ returnvalue);
}
}
輸出:
Instant before truncate: 2018-12-30T09:24:54.630Z Instant after truncate: 2018-12-30T00:00:00Z
程序3:顯示異常:
// Java program to demonstrate
// Instant.truncatedTo() method
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
// create a Instant object
Instant instant
= Instant.parse("2018-12-30T09:24:54.63Z");
try {
instant.truncatedTo(ChronoUnit.ERAS);
}
catch (Exception e) {
// print result
System.out.println("Exception: " + e);
}
}
}
輸出:
Exception: java.time.temporal.UnsupportedTemporalTypeException: Unit is too large to be used for truncation
參考:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#truncatedTo(java.time.temporal.TemporalUnit)
相關用法
- Java LocalTime truncatedTo()用法及代碼示例
- Java ZonedDateTime truncatedTo()用法及代碼示例
- Java Duration truncatedTo(TemporalUnit)用法及代碼示例
- Java Instant until()用法及代碼示例
- Java Instant from()用法及代碼示例
- Java Instant get()用法及代碼示例
- Java Instant with()用法及代碼示例
- Java Instant plus()用法及代碼示例
- Java Instant now()用法及代碼示例
- Java Instant minus()用法及代碼示例
- Java Instant minusMillis()用法及代碼示例
- Java Instant getNano()用法及代碼示例
- Java Instant hashCode()用法及代碼示例
- Java Instant toEpochMilli()用法及代碼示例
- Java Instant isAfter()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Instant truncatedTo() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。