700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java 8 新日期时间 API ( 下 ) – 时区日期时间

Java 8 新日期时间 API ( 下 ) – 时区日期时间

时间:2022-12-07 09:35:47

相关推荐

Java 8 新日期时间 API ( 下 ) – 时区日期时间

引言

上一章节Java 8新日期时间API( 上 ) – 本地日期时间 我们对Java 8重新设计的日期时间API做了一些基础的介绍,同时详细介绍了和本地时间有关的几个类LocalDateTime 、LocalDate 和 LocalTime

我同时也发现,这三个类没有任何时区相关的信息,但也不能说它们没处理时区,而只能说它们有选择的隐藏了时区的处理。它们内部会使用操作系统当前的时区。

以此同时,Javajava.time包中也提供了几个类用于处理需要关注时区的日期时间API。它们是java.time.ZonedDateTimejava.time.ZoneId。前者用于处理需要时区的日期时间,后者用于处理时区。

ZonedDateTimeLocalDateTime类似,几乎有着相同的API。从某些方面说,ZonedLocalTime如果不传递时区信息,那么它会默认使用操作系统的时区,这样,结果其实和LocalDateTime是类似的。

比如,我们可以使用ZonedDateTimenow()方法返回当前时区 ( 操作系统时区 ) 的日期时间,调用parse()方法可以将一个包含了时区信息的字符串格式的日期时间转化为一个ZonedDateTime实例。

简单使用ZonedDateTime示例

import org.junit.jupiter.api.Test;import java.time.LocalDate;import java.time.LocalTime;import java.time.ZonedDateTime;public class ZonedDateTimeTest {/*** 简单测试ZonedDateTime*/@Testpublic void zonedDateTimeTest(){ZonedDateTime now = ZonedDateTime.now();System.out.println("当前日期时间是:" + now);//解析String到ZonedDateTimeZonedDateTime datetime = ZonedDateTime.parse("-10-10T21:58:00+08:00");System.out.println("日期时间是:" + datetime);//转换成为LocalDateLocalDate localDate = now.toLocalDate();System.out.println("当前日期是:" + localDate);//转换成为LocalTime localTime = now.toLocalTime();System.out.println("当前时间是:" + localTime);}}/*返回结果当前日期时间是:-11-10T18:34:53.395+08:00[Asia/Shanghai]日期时间是:-10-10T21:58+08:00当前日期是:-11-10当前时间是:18:34:53.395*/

处理时区

时区相关的信息,我们可以使用ZoneId类来处理。比如可以调用ZoneId类的静态方法systemDefault()返回当前的时区。

我们还可以调用ZonedDateTime实例的getZone()方法获取实例所在的时区

import org.junit.jupiter.api.Test;import java.text.ParseException;import java.text.SimpleDateFormat;import java.time.OffsetDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeFormatterBuilder;import java.time.temporal.ChronoField;public class ZonedDateTimeTest {/*** 简单测试ZonedDateTime*/@Testpublic void zonedDateTimeTest() throws ParseException {/*** 获取时区的两种方法*/ZoneId currentZone = ZoneId.systemDefault();System.out.println("当前时区是: " + currentZone);ZonedDateTime now = ZonedDateTime.now();System.out.println("当前时区是: " + now.getZone());/*** 设置当前时区*/ZoneId id = ZoneId.of("Europe/Paris");System.out.println("ZoneId: " + id);currentZone = ZoneId.systemDefault();System.out.println("当期时区: " + currentZone);/*** 解析时间*/SimpleDateFormat sdf = new SimpleDateFormat("yyyy--MM--dd");System.out.println(sdf.parse("--02--01"));DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").parseDefaulting(ChronoField.NANO_OF_DAY, 0).toFormatter().withZone(ZoneId.of("Europe/Berlin"));ZonedDateTime parse = ZonedDateTime.parse("-11-13", formatter);System.out.println(parse);OffsetDateTime offsetDateTime = parse.toOffsetDateTime();System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_DATE));}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。