Java中 ZonedDateTime ofStrict() 方法及示例
ZonedDateTime类的ofStrict()方法用于创建 ZonedDateTime 的实例,严格验证本地日期时间、偏移量和区域 ID 的组合,其中所有三个本地日期时间、ZoneOffset 和 ZoneId 作为参数传递。如果偏移量无效,抛出异常。
句法:
public static ZonedDateTime ofStrict(LocalDateTime localDateTime,
ZoneOffset offset,
ZoneId zone)
参数:此方法接受三个参数localDateTime是本地日期时间, offset是区域偏移量和zone是时区。
返回值:此方法返回分区的日期时间。
下面的程序说明了 ofStrict() 方法:
方案一:
Java
// 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);
}
}
Java
// 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:59+01:00[Europe/Paris]
方案二:
Java
// 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 Java , Java Java)