Java ZonedDateTime ofStrict()方法及示例
ZonedDateTime 类的 ofStrict() 方法用于创建一个ZonedDateTime的实例,严格验证本地日期时间、偏移量和区域ID的组合,其中所有三个本地日期时间、ZoneOffset和ZoneId都作为参数传递。如果偏移量无效,就会抛出一个异常。
语法:
public static ZonedDateTime ofStrict(LocalDateTime localDateTime,
ZoneOffset offset,
ZoneId zone)
参数: 该方法接受三个参数 localDateTime (本地日期时间)、 offset (区域偏移)和 zone (时区)。
返回值: 该方法返回分区日期时间。
以下程序说明ofStrict()方法:
程序1:
// Java program to demonstrate
// ZonedDateTime.ofStrict() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create local date time object
LocalDateTime ldt
= LocalDateTime
.parse("2019-01-29T23:55:59.00");
// create ZoneOffset
ZoneOffset zoneOffset
= ZoneOffset.ofHours(1);
// create a ZonID
ZoneId zone
= ZoneId.of("Europe/Paris");
// apply ofStrict method
// of ZonedDateTime class
ZonedDateTime zt
= ZonedDateTime
.ofStrict(
ldt, zoneOffset, zone);
// print the result
System.out.println("ZonedDateTime is "
+ zt);
}
}
输出
ZonedDateTime is 2019-01-29T23:55:59+01:00[Europe/Paris]
程序2
// Java program to demonstrate
// ZonedDateTime.ofStrict() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create local date-time object
LocalDateTime ldt
= LocalDateTime
.parse("2019-01-29T23:55:59.00");
// create ZoneOffset
ZoneOffset zoneOffset
= ZoneOffset.ofHours(0);
// create a ZonID
ZoneId zone = ZoneId.of("UTC");
// apply ofStrict method
// of ZonedDateTime class
ZonedDateTime zt
= ZonedDateTime
.ofStrict(
ldt, zoneOffset, zone);
// print the result
System.out.println("ZonedDateTime is "
+ zt);
}
}
输出
ZonedDateTime is 2019-01-29T23:55:59Z[UTC]
参考:
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#ofStrict(java.time.LocalDateTime, java.time.ZoneOffset, java.time.ZoneId)