Java教程

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() 它用于获取时区,例如"亚洲/加尔各答"。
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]
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4