Java教程-Java ZonedDateTime类

Java ZonedDateTime类
Java ZonedDateTime类是一个带有时区的日期时间的不可变表示。它继承自Object类并实现了ChronoZonedDateTime接口。
ZonedDateTime类用于存储所有日期和时间字段,精确到纳秒,并使用区域偏移处理模糊的本地日期时间
Java ZonedDateTime类声明
让我们来看一下java.time.ZonedDateTime类的声明。
public final class ZonedDateTime extends Object
implements Temporal, ChronoZonedDateTime<LocalDate>, Serializable
Java ZonedDateTime的方法
方法 | 描述 |
---|---|
String format(DateTimeFormatter formatter) | 用于使用指定的格式化程序对此日期时间进行格式化。 |
int get(TemporalField field) | 用于从此日期时间中获取指定字段的值作为整数。 |
ZoneId getZone() | 用于获取时区,例如 'Asia/Kolkata'。 |
ZonedDateTime withZoneSameInstant(ZoneId zone) | 用于返回具有不同时区的此日期时间的副本,保留即时时间。 |
static ZonedDateTime now() | 用于在默认时区从系统时钟获取当前日期时间。 |
static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone) | 用于从本地日期和时间获取ZonedDateTime的实例。 |
ZonedDateTime minus(long amountToSubtract, TemporalUnit unit) | 用于返回减去指定数量后的此日期时间的副本。 |
ZonedDateTime plus(long amountToAdd, TemporalUnit unit) | 用于返回添加指定数量后的此日期时间的副本。 |
Java ZonedDateTime类示例
import java.time.ZonedDateTime;
public class ZonedDateTimeExample1{
public static void main(String[] args) {
ZonedDateTime zone = ZonedDateTime.parse("2016-10-05T08:20:10+05:30[Asia/Kolkata]");
System.out.println(zone);
}
}
输出:
2016-10-05T08:20:10+05:30[Asia/Kolkata]
Java ZonedDateTime类示例:of()和withZoneSameInstant()
import java.time.*;
public class ZonedDateTimeExample2{
public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.of(2017, Month.JANUARY, 19, 15, 26);
ZoneId india = ZoneId.of("Asia/Kolkata");
ZonedDateTime zone1 = ZonedDateTime.of(ldt, india);
System.out.println("In India Central Time Zone: " + zone1);
ZoneId tokyo = ZoneId.of("Asia/Tokyo");
ZonedDateTime zone2 = zone1.withZoneSameInstant(tokyo);
System.out.println("In Tokyo Central Time Zone:" + zone2);
}
}
输出:
In India Central Time Zone: 2017-01-19T15:26+05:30[Asia/Kolkata]
In Tokyo Central Time Zone:2017-01-19T18:56+09:00[Asia/Tokyo]
Java ZonedDateTime类示例:getZone()
import java.time.ZonedDateTime;
public class ZonedDateTimeExample3{
public static void main(String[] args) {
ZonedDateTime zone =ZonedDateTime.now();
System.out.println(zone.getZone());
}
}
输出:
Asia/Kolkata
Java ZonedDateTime类示例:minus()
import java.time.Period;
import java.time.ZonedDateTime;
public class ZonedDateTimeExample4 {
public static void main(String[] args) {
ZonedDateTime zone= ZonedDateTime.now();
ZonedDateTime m = zone.minus(Period.ofDays(126));
System.out.println(m);
}
}
输出:
2016-09-15T12:54:01.354+05:30[Asia/Kolkata]
Java ZonedDateTime类示例:plus()
import java.time.*;
public class ZonedDateTimeExample5{
public static void main(String[] args) {
ZonedDateTime zone= ZonedDateTime.now();
ZonedDateTime p = zone.plus(Period.ofDays(126));
System.out.println(p);
}
}
输出:
2017-05-25T12:56:12.417+05:30[Asia/Kolkata]