Java ZonedDateTime truncatedTo()方法及示例
ZonedDateTime 类的 truncatedTo() 方法是用来返回这个ZonedDateTime在指定单位中的值。这个方法需要一个参数Unit,它是这个ZonedDateTime要被截断的单位。它返回一个截断的不可变的ZonedDateTime,其值为指定单位。
语法
public ZonedDateTime truncatedTo(TemporalUnit unit)
参数: 该方法接受一个单一的参数 unit ,它是这个ZonedDateTime要被截断的单位。它不应该是空的。
返回值: 该方法返回一个 不可改变的截断的ZonedDateTime ,其值为指定单位。
异常: 该方法会抛出以下异常。
- DateTimeException: 如果无法截断。
- UnsupportedTemporalTypeException: 如果单位不被支持。
下面的程序说明了truncatedTo()方法。
程序1 :
// Java program to demonstrate
// ZonedDateTime.truncatedTo() method
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
// create a ZonedDateTime object
ZonedDateTime zonedDT
= ZonedDateTime
.parse(
"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
// print ZonedDateTime
System.out.println("ZonedDateTime before"
+ " truncate: "
+ zonedDT);
// truncate to ChronoUnit.HOURS
// means unit smaller than Hour
// will be Zero
ZonedDateTime returnvalue
= zonedDT.truncatedTo(ChronoUnit.HOURS);
// print result
System.out.println("ZonedDateTime after "
+ " truncate: "
+ returnvalue);
}
}
输出。
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after truncate: 2018-12-06T19:00+05:30[Asia/Calcutta]
程序2
// Java program to demonstrate
// ZonedDateTime.truncatedTo() method
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
// create a ZonedDateTime object
ZonedDateTime zonedDT
= ZonedDateTime
.parse(
"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
// print ZonedDateTime
System.out.println("ZonedDateTime before"
+ " truncate: "
+ zonedDT);
// truncate to ChronoUnit.DAYS
// means unit smaller than DAY
// will be Zero
ZonedDateTime returnvalue
= zonedDT.truncatedTo(ChronoUnit.DAYS);
// print result
System.out.println("ZonedDateTime after "
+ " truncate: "
+ returnvalue);
}
}
输出。
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after truncate: 2018-12-06T00:00+05:30[Asia/Calcutta]
参考资料: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withZoneSameInstant(java.time.ZoneId)