gpt4 book ai didi

org.threeten.bp.ZoneId类的使用及代码示例

转载 作者:知者 更新时间:2024-03-15 04:32:49 37 4
gpt4 key购买 nike

本文整理了Java中org.threeten.bp.ZoneId类的一些代码示例,展示了ZoneId类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ZoneId类的具体详情如下:
包路径:org.threeten.bp.ZoneId
类名称:ZoneId

ZoneId介绍

[英]A time-zone ID, such as Europe/Paris.

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
    Most fixed offsets are represented by ZoneOffset. Calling #normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

The actual rules, describing when and how the offset changes, are defined by ZoneRules. This class is simply an ID used to obtain the underlying rules. This approach is taken because rules are defined by governments and change frequently, whereas the ID is stable.

The distinction has other effects. Serializing the ZoneId will only send the ID, whereas serializing the rules sends the entire data set. Similarly, a comparison of two IDs only examines the ID, whereas a comparison of two rules examines the entire data set.

Time-zone IDs

The ID is unique within the system. There are three types of ID.

The simplest type of ID is that from ZoneOffset. This consists of 'Z' and IDs starting with '+' or '-'.

The next type of ID are offset-style IDs with some form of prefix, such as 'GMT+2' or 'UTC+01:00'. The recognised prefixes are 'UTC', 'GMT' and 'UT'. The offset is the suffix and will be normalized during creation. These IDs can be normalized to a ZoneOffset using normalized().

The third type of ID are region-based IDs. A region-based ID must be of two or more characters, and not start with 'UTC', 'GMT', 'UT' '+' or '-'. Region-based IDs are defined by configuration, see ZoneRulesProvider. The configuration focuses on providing the lookup from the ID to the underlying ZoneRules.

Time-zone rules are defined by governments and change frequently. There are a number of organizations, known here as groups, that monitor time-zone changes and collate them. The default group is the IANA Time Zone Database (TZDB). Other organizations include IATA (the airline industry body) and Microsoft.

Each group defines its own format for the region ID it provides. The TZDB group defines IDs such as 'Europe/London' or 'America/New_York'. TZDB IDs take precedence over other groups.

It is strongly recommended that the group name is included in all IDs supplied by groups other than TZDB to avoid conflicts. For example, IATA airline time-zone region IDs are typically the same as the three letter airport code. However, the airport of Utrecht has the code 'UTC', which is obviously a conflict. The recommended format for region IDs from groups other than TZDB is 'group~region'. Thus if IATA data were defined, Utrecht airport would be 'IATA~UTC'.

Serialization

This class can be serialized and stores the string zone ID in the external form. The ZoneOffset subclass uses a dedicated format that only stores the offset from UTC/Greenwich.

A ZoneId can be deserialized in a Java Runtime where the ID is unknown. For example, if a server-side Java Runtime has been updated with a new zone ID, but the client-side Java Runtime has not been updated. In this case, the ZoneIdobject will exist, and can be queried using getId, equals, hashCode, toString, getDisplayName and normalized. However, any call to getRules will fail with ZoneRulesException. This approach is designed to allow a ZonedDateTime to be loaded and queried, but not modified, on a Java Runtime with incomplete time-zone information.

Specification for implementors

This abstract class has two implementations, both of which are immutable and thread-safe. One implementation models region-based IDs, the other is ZoneOffset modelling offset-based IDs. This difference is visible in serialization.
[中]时区ID,例如欧洲/巴黎。
ZoneId用于标识用于在Instant和LocalDateTime之间转换的规则。有两种不同类型的ID:
*固定偏移量-从UTC/格林威治时间完全解析的偏移量,对所有本地日期时间使用相同的偏移量
*地理区域——适用于查找UTC/格林威治偏移量的一组特定规则的区域
大多数固定偏移由ZoneOffset表示。在任何ZoneId上调用#normalized()将确保固定偏移ID将表示为ZoneOffset。
描述偏移量何时以及如何更改的实际规则由ZoneRules定义。这个类只是一个用来获取底层规则的ID。之所以采用这种方法,是因为规则由政府定义并经常更改,而ID是稳定的。
这种区别还有其他影响。序列化ZoneId只会发送ID,而序列化规则会发送整个数据集。类似地,两个ID的比较只检查ID,而两个规则的比较检查整个数据集。
####时区ID
ID在系统中是唯一的。有三种类型的ID。
最简单的ID类型是来自ZoneOffset的ID。它由“Z”和以“+”或“-”开头的ID组成。
下一种类型的ID是带有某种形式前缀的偏移样式ID,例如“GMT+2”或“UTC+01:00”。可识别的前缀为“UTC”、“GMT”和“UT”。偏移量是后缀,将在创建期间标准化。可以使用normalized()将这些ID规范化为区域偏移。
第三种类型的ID是基于区域的ID。基于区域的ID必须包含两个或多个字符,且不能以“UTC”、“GMT”、“UT”+”或“-”开头。基于区域的ID由配置定义,请参阅ZoneRulesProvider。配置的重点是提供从ID到底层ZoneRules的查找。
时区规则由政府定义,并且经常变化。有许多组织,这里称为小组,负责监控时区变化并对其进行整理。默认组是IANA时区数据库(TZDB)。其他组织包括国际航空运输协会(IATA)和微软。
每个组为其提供的区域ID定义自己的格式。TZDB集团定义了“欧洲/伦敦”或“美国/纽约”等ID。TZDB ID优先于其他组。
强烈建议将组名包含在除TZDB以外的组提供的所有ID中,以避免冲突。例如,IATA航空公司时区区域ID通常与三个字母的机场代码相同。然而,乌得勒支机场的代码为“UTC”,这显然是一种冲突。来自TZDB以外的组的区域ID的建议格式为“group~region”。因此,如果定义了IATA数据,乌得勒支机场将是“IATA~UTC”。
####系列化
此类可以序列化,并以外部形式存储字符串区域ID。ZoneOffset子类使用一种专用格式,只存储UTC/Greenwich的偏移量。
ZoneId可以在ID未知的Java运行时中反序列化。例如,如果服务器端Java运行时已使用新的区域ID更新,但客户端Java运行时尚未更新。在这种情况下,ZoneIdobject将存在,并且可以使用getId、equals、hashCode、toString、getDisplayName和normalized进行查询。但是,任何对getRules的调用都将失败,并出现ZoneRules异常。这种方法旨在允许在时区信息不完整的Java运行时上加载和查询ZonedDateTime,而不是修改它。
####实施者规范
这个抽象类有两个实现,它们都是不可变的和线程安全的。一种实现是基于区域的IDs建模,另一种实现是基于区域偏移的IDs建模。这种差异在序列化中是显而易见的。

代码示例

代码示例来源:origin: gabrielittner/lazythreetenbp

/**
 * Call on background thread to eagerly load all zones. Starts with loading
 * {@link ZoneId#systemDefault()} which is the one most likely to be used.
 */
@WorkerThread
public static void cacheZones() {
  ZoneId.systemDefault().getRules();
  for (String zoneId : ZoneRulesProvider.getAvailableZoneIds()) {
    ZoneRulesProvider.getRules(zoneId, true);
  }
}

代码示例来源:origin: ThreeTen/threetenbp

/**
 * Converts a {@code TimeZone} to a {@code ZoneId}.
 * 
 * @param timeZone  the time-zone, not null
 * @return the zone, not null
 */
public static ZoneId toZoneId(TimeZone timeZone) {
  return ZoneId.of(timeZone.getID(), ZoneId.SHORT_IDS);
}

代码示例来源:origin: apache/servicemix-bundles

@Nonnull
  @Override
  public String convert(ZoneId source) {
    return source.toString();
  }
}

代码示例来源:origin: ThreeTen/threetenbp

@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
  // this is a poor implementation that handles some but not all of the spec
  // JDK8 has a lot of extra information here
  Map<String, String> ids = new TreeMap<String, String>(LENGTH_COMPARATOR);
  for (String id : ZoneId.getAvailableZoneIds()) {
    ids.put(id, id);
    TimeZone tz = TimeZone.getTimeZone(id);
    int tzstyle = (textStyle.asNormal() == TextStyle.FULL ? TimeZone.LONG : TimeZone.SHORT);
    String textWinter = tz.getDisplayName(false, tzstyle, context.getLocale());
    if (id.startsWith("Etc/") || (!textWinter.startsWith("GMT+") && !textWinter.startsWith("GMT+"))) {
      ids.put(textWinter, id);
    }
    String textSummer = tz.getDisplayName(true, tzstyle, context.getLocale());
    if (id.startsWith("Etc/") || (!textSummer.startsWith("GMT+") && !textSummer.startsWith("GMT+"))) {
      ids.put(textSummer, id);
    }
  }
  for (Entry<String, String> entry : ids.entrySet()) {
    String name = entry.getKey();
    if (context.subSequenceEquals(text, position, name, 0, name.length())) {
      context.setParsed(ZoneId.of(entry.getValue()));
      return position + name.length();
    }
  }
  return ~position;
}

代码示例来源:origin: ThreeTen/threetenbp

/**
 * Normalizes the time-zone ID, returning a {@code ZoneOffset} where possible.
 * <p>
 * The returns a normalized {@code ZoneId} that can be used in place of this ID.
 * The result will have {@code ZoneRules} equivalent to those returned by this object,
 * however the ID returned by {@code getId()} may be different.
 * <p>
 * The normalization checks if the rules of this {@code ZoneId} have a fixed offset.
 * If they do, then the {@code ZoneOffset} equal to that offset is returned.
 * Otherwise {@code this} is returned.
 *
 * @return the time-zone unique ID, not null
 */
public ZoneId normalized() {
  try {
    ZoneRules rules = getRules();
    if (rules.isFixedOffset()) {
      return rules.getOffset(Instant.EPOCH);
    }
  } catch (ZoneRulesException ex) {
    // ignore invalid objects
  }
  return this;
}

代码示例来源:origin: org.threeten/threetenbp

/**
 * Obtains a clock that returns the current instant using the best available
 * system clock, converting to date and time using the default time-zone.
 * <p>
 * This clock is based on the best available system clock.
 * This may use {@link System#currentTimeMillis()}, or a higher resolution
 * clock if one is available.
 * <p>
 * Using this method hard codes a dependency to the default time-zone into your application.
 * It is recommended to avoid this and use a specific time-zone whenever possible.
 * The {@link #systemUTC() UTC clock} should be used when you need the current instant
 * without the date or time.
 * <p>
 * The returned implementation is immutable, thread-safe and {@code Serializable}.
 * It is equivalent to {@code system(ZoneId.systemDefault())}.
 *
 * @return a clock that uses the best available system clock in the default zone, not null
 * @see ZoneId#systemDefault()
 */
public static Clock systemDefaultZone() {
  return new SystemClock(ZoneId.systemDefault());
}

代码示例来源:origin: ThreeTen/threetenbp

@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
  ZoneId zone = context.getValue(TemporalQueries.zoneId());
  if (zone == null) {
    return false;
  }
  if (zone.normalized() instanceof ZoneOffset) {
    buf.append(zone.getId());
    return true;
  }
  TemporalAccessor temporal = context.getTemporal();
  boolean daylight = false;
  if (temporal.isSupported(INSTANT_SECONDS)) {
    Instant instant = Instant.ofEpochSecond(temporal.getLong(INSTANT_SECONDS));
    daylight = zone.getRules().isDaylightSavings(instant);
  }
  TimeZone tz = TimeZone.getTimeZone(zone.getId());
  int tzstyle = (textStyle.asNormal() == TextStyle.FULL ? TimeZone.LONG : TimeZone.SHORT);
  String text = tz.getDisplayName(daylight, tzstyle, context.getLocale());
  buf.append(text);
  return true;
}

代码示例来源:origin: org.threeten/threetenbp

@Override
public boolean equals(Object obj) {
  if (obj instanceof SystemClock) {
    return zone.equals(((SystemClock) obj).zone);
  }
  return false;
}
@Override

代码示例来源:origin: ThreeTen/threetenbp

ZoneId normalizedOffset = overrideZone.normalized();
ZoneOffset temporalOffset = temporal.query(TemporalQueries.offset());
if (normalizedOffset instanceof ZoneOffset && temporalOffset != null && normalizedOffset.equals(temporalOffset) == false) {
  throw new DateTimeException("Invalid override zone for temporal: " + overrideZone + " " + temporal);

代码示例来源:origin: org.threeten/threetenbp

/**
 * Normalizes the time-zone ID, returning a {@code ZoneOffset} where possible.
 * <p>
 * The returns a normalized {@code ZoneId} that can be used in place of this ID.
 * The result will have {@code ZoneRules} equivalent to those returned by this object,
 * however the ID returned by {@code getId()} may be different.
 * <p>
 * The normalization checks if the rules of this {@code ZoneId} have a fixed offset.
 * If they do, then the {@code ZoneOffset} equal to that offset is returned.
 * Otherwise {@code this} is returned.
 *
 * @return the time-zone unique ID, not null
 */
public ZoneId normalized() {
  try {
    ZoneRules rules = getRules();
    if (rules.isFixedOffset()) {
      return rules.getOffset(Instant.EPOCH);
    }
  } catch (ZoneRulesException ex) {
    // ignore invalid objects
  }
  return this;
}

代码示例来源:origin: ThreeTen/threetenbp

/**
 * Obtains a clock that returns the current instant using the best available
 * system clock, converting to date and time using the default time-zone.
 * <p>
 * This clock is based on the best available system clock.
 * This may use {@link System#currentTimeMillis()}, or a higher resolution
 * clock if one is available.
 * <p>
 * Using this method hard codes a dependency to the default time-zone into your application.
 * It is recommended to avoid this and use a specific time-zone whenever possible.
 * The {@link #systemUTC() UTC clock} should be used when you need the current instant
 * without the date or time.
 * <p>
 * The returned implementation is immutable, thread-safe and {@code Serializable}.
 * It is equivalent to {@code system(ZoneId.systemDefault())}.
 *
 * @return a clock that uses the best available system clock in the default zone, not null
 * @see ZoneId#systemDefault()
 */
public static Clock systemDefaultZone() {
  return new SystemClock(ZoneId.systemDefault());
}

代码示例来源:origin: org.threeten/threetenbp

@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
  ZoneId zone = context.getValue(TemporalQueries.zoneId());
  if (zone == null) {
    return false;
  }
  if (zone.normalized() instanceof ZoneOffset) {
    buf.append(zone.getId());
    return true;
  }
  TemporalAccessor temporal = context.getTemporal();
  boolean daylight = false;
  if (temporal.isSupported(INSTANT_SECONDS)) {
    Instant instant = Instant.ofEpochSecond(temporal.getLong(INSTANT_SECONDS));
    daylight = zone.getRules().isDaylightSavings(instant);
  }
  TimeZone tz = TimeZone.getTimeZone(zone.getId());
  int tzstyle = (textStyle.asNormal() == TextStyle.FULL ? TimeZone.LONG : TimeZone.SHORT);
  String text = tz.getDisplayName(daylight, tzstyle, context.getLocale());
  buf.append(text);
  return true;
}

代码示例来源:origin: org.threeten/threetenbp

@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
  // this is a poor implementation that handles some but not all of the spec
  // JDK8 has a lot of extra information here
  Map<String, String> ids = new TreeMap<String, String>(LENGTH_COMPARATOR);
  for (String id : ZoneId.getAvailableZoneIds()) {
    ids.put(id, id);
    TimeZone tz = TimeZone.getTimeZone(id);
    int tzstyle = (textStyle.asNormal() == TextStyle.FULL ? TimeZone.LONG : TimeZone.SHORT);
    String textWinter = tz.getDisplayName(false, tzstyle, context.getLocale());
    if (id.startsWith("Etc/") || (!textWinter.startsWith("GMT+") && !textWinter.startsWith("GMT+"))) {
      ids.put(textWinter, id);
    }
    String textSummer = tz.getDisplayName(true, tzstyle, context.getLocale());
    if (id.startsWith("Etc/") || (!textSummer.startsWith("GMT+") && !textSummer.startsWith("GMT+"))) {
      ids.put(textSummer, id);
    }
  }
  for (Entry<String, String> entry : ids.entrySet()) {
    String name = entry.getKey();
    if (context.subSequenceEquals(text, position, name, 0, name.length())) {
      context.setParsed(ZoneId.of(entry.getValue()));
      return position + name.length();
    }
  }
  return ~position;
}

代码示例来源:origin: ThreeTen/threetenbp

@Override
public boolean equals(Object obj) {
  if (obj instanceof SystemClock) {
    return zone.equals(((SystemClock) obj).zone);
  }
  return false;
}
@Override

代码示例来源:origin: org.threeten/threetenbp

ZoneId normalizedOffset = overrideZone.normalized();
ZoneOffset temporalOffset = temporal.query(TemporalQueries.offset());
if (normalizedOffset instanceof ZoneOffset && temporalOffset != null && normalizedOffset.equals(temporalOffset) == false) {
  throw new DateTimeException("Invalid override zone for temporal: " + overrideZone + " " + temporal);

代码示例来源:origin: XeroAPI/Xero-Java

@Override
 public OffsetDateTime apply(OffsetDateTime d, ZoneId z) {
  return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime()));
 }
}

代码示例来源:origin: apache/servicemix-bundles

@Nonnull
  @Override
  public LocalDateTime convert(Date source) {
    return ofInstant(toInstant(source), systemDefault());
  }
}

代码示例来源:origin: org.threeten/threetenbp

/**
 * Converts a {@code TimeZone} to a {@code ZoneId}.
 * 
 * @param timeZone  the time-zone, not null
 * @return the zone, not null
 */
public static ZoneId toZoneId(TimeZone timeZone) {
  return ZoneId.of(timeZone.getID(), ZoneId.SHORT_IDS);
}

代码示例来源:origin: ThreeTen/threetenbp

/**
 * Outputs this date-time as a {@code String}, such as
 * {@code 2007-12-23T10:15:30+01:00[Europe/Paris]}.
 * <p>
 * The format consists of the {@code LocalDateTime} followed by the {@code ZoneOffset}.
 * If the {@code ZoneId} is not the same as the offset, then the ID is output.
 * The output is compatible with ISO-8601 if the offset and ID are the same.
 *
 * @return a string representation of this date-time, not null
 */
@Override  // override for Javadoc
public String toString() {
  String str = dateTime.toString() + offset.toString();
  if (offset != zone) {
    str += '[' + zone.toString() + ']';
  }
  return str;
}

代码示例来源:origin: org.threeten/threetenbp

@Override
public Clock withZone(ZoneId zone) {
  if (zone.equals(this.zone)) {  // intentional NPE
    return this;
  }
  return new SystemClock(zone);
}
@Override

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com