引言
上一章节 Java 8
新日期时间 API
( 上 ) – 本地日期时间 我们对 Java 8
重新设计的日期时间 API
做了一些基础的介绍,同时详细介绍了和本地时间有关的几个类 LocalDateTime 、LocalDate 和 LocalTime
。
我同时也发现,这三个类没有任何时区相关的信息,但也不能说它们没处理时区,而只能说它们有选择的隐藏了时区的处理。它们内部会使用操作系统当前的时区。
以此同时,Java
在 java.time
包中也提供了几个类用于处理需要关注时区的日期时间 API
。它们是 java.time.ZonedDateTime
和 java.time.ZoneId
。前者用于处理需要时区的日期时间,后者用于处理时区。
ZonedDateTime
和 LocalDateTime
类似,几乎有着相同的 API
。从某些方面说,ZonedLocalTime
如果不传递时区信息,那么它会默认使用操作系统的时区,这样,结果其实和 LocalDateTime
是类似的。
比如,我们可以使用 ZonedDateTime
的 now()
方法返回当前时区 ( 操作系统时区 ) 的日期时间,调用 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
*/
@Test
public void zonedDateTimeTest(){
ZonedDateTime now = ZonedDateTime.now();
System.out.println("当前日期时间是:" + now);
//解析String到ZonedDateTime
ZonedDateTime datetime = ZonedDateTime.parse("2012-10-10T21:58:00+08:00");
System.out.println("日期时间是:" + datetime);
//转换成为LocalDate
LocalDate localDate = now.toLocalDate();
System.out.println("当前日期是:" + localDate);
//转换成为
LocalTime localTime = now.toLocalTime();
System.out.println("当前时间是:" + localTime);
}
}
/*
返回结果
当前日期时间是:2021-11-10T18:34:53.395+08:00[Asia/Shanghai]
日期时间是:2012-10-10T21:58+08:00
当前日期是:2021-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
*/
@Test
public 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("2020--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("2015-11-13", formatter);
System.out.println(parse);
OffsetDateTime offsetDateTime = parse.toOffsetDateTime();
System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_DATE));
}
}