📜  Java8 ZoneOffset类

📅  最后修改于: 2020-10-01 06:37:57             🧑  作者: Mango

Java ZoneOffset类

Java ZoneOffset类用于表示相对于UTC时区的固定区域偏移量。它继承了ZoneId类并实现Comparable接口。

ZoneOffset类声明三个常量:

  • MAX:这是支持的最大区域偏移量。
  • MIN:这是支持的最小区域偏移量。
  • UTC:这是UTC的时区偏移常数。

Java ZoneOffset类声明

我们来看一下java.time.ZoneOffset类的声明。

public final class ZoneOffset extends ZoneId 
implements TemporalAccessor, TemporalAdjuster, Comparable, Serializable

Java ZoneOffset的方法

Method Description
Temporal adjustInto(Temporal temporal) It is used to adjust the specified temporal object to have the same offset as this object.
int get(TemporalField field) It is used to get the value of the specified field from this offset as an int.
boolean isSupported(TemporalField field) It is used to check if the specified field is supported.
static ZoneOffset of(String offsetId) It is used to obtain an instance of ZoneOffset using the ID.
static ZoneOffset ofHours(int hours) It is used to obtain an instance of ZoneOffset using an offset in hours.
static ZoneOffset ofHoursMinutes(int hours, int minutes) It is used to obtain an instance of ZoneOffset using an offset in hours and minutes.
ValueRange range(TemporalField field) It is used to get the range of valid values

Java ZoneOffset示例

import java.time.*;
import java.time.temporal.Temporal;
public class ZoneOffsetExample1 {
  public static void main(String[] args) {
    ZoneOffset zone = ZoneOffset.UTC;
    Temporal temp = zone.adjustInto(ZonedDateTime.now());
    System.out.println(temp);
  }
}

输出:

2017-01-29T12:43:00.702+05:30[Asia/Calcutta]

Java ZoneOffset示例:ofHours()

import java.time.ZoneOffset;
public class ZoneOffsetExample2 {
  public static void main(String[] args) {
    ZoneOffset zone = ZoneOffset.ofHours(5);
    System.out.println(zone);
  }
}

输出:

+05:00

Java ZoneOffset示例:ofHoursMinutes()

import java.time.ZoneOffset;
public class ZoneOffsetExample3 {
  public static void main(String[] args) {
    ZoneOffset zone = ZoneOffset.ofHoursMinutes(5,30);
    System.out.println(zone);
  }
}

输出:

+05:30

Java ZoneOffset示例:isSupported()

import java.time.ZoneOffset;
import java.time.temporal.ChronoField;
public class ZoneOffsetExample4 {
  public static void main(String[] args) {
    ZoneOffset zone = ZoneOffset.UTC;
    boolean b1 = zone.isSupported(ChronoField.OFFSET_SECONDS);
    System.out.println(b1);
    boolean b2 = zone.isSupported(ChronoField.SECOND_OF_MINUTE);
    System.out.println(b2);
  }
}

输出:

true
false