java.time.zone.ZoneRules类的使用及代码示例

x33g5p2x  于2022-02-05 转载在 其他  
字(13.1k)|赞(0)|评价(0)|浏览(115)

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

ZoneRules介绍

[英]The rules defining how the zone offset varies for a single time-zone.

The rules model all the historic and future transitions for a time-zone. ZoneOffsetTransition is used for known transitions, typically historic. ZoneOffsetTransitionRule is used for future transitions that are based on the result of an algorithm.

The rules are loaded via ZoneRulesProvider using a ZoneId. The same rules may be shared internally between multiple zone IDs.

Serializing an instance of ZoneRules will store the entire set of rules. It does not store the zone ID as it is not part of the state of this object.

A rule implementation may or may not store full information about historic and future transitions, and the information stored is only as accurate as that supplied to the implementation by the rules provider. Applications should treat the data provided as representing the best information available to the implementation of this rule.

Specification for implementors

The supplied implementations of this class are immutable and thread-safe.
[中]定义单个时区的分区偏移量如何变化的规则。
这些规则为时区的所有历史和未来过渡建模。ZoneOffsetTransition用于已知的过渡,通常是历史过渡。ZoneOffsetTransitionRule用于基于算法结果的未来转换。
使用ZoneId通过ZoneRulesProvider加载规则。多个区域ID之间可以在内部共享相同的规则。
序列化ZoneRules实例将存储整个规则集。它不存储区域ID,因为它不是此对象状态的一部分。
规则实现可能存储也可能不存储有关历史和未来转换的完整信息,存储的信息仅与规则提供程序提供给实现的信息一样准确。应用程序应将提供的数据视为代表执行此规则所需的最佳信息。
####实施者规范
提供的此类实现是不可变的,并且是线程安全的。

代码示例

代码示例来源:origin: neo4j/neo4j

private static ZoneOffset parseOffset( Matcher matcher, Supplier<ZoneId> defaultZone )
{
  ZoneOffset offset = parseOffset( matcher );
  if ( offset == null )
  {
    ZoneId zoneId = defaultZone.get();
    offset = zoneId instanceof ZoneOffset ? (ZoneOffset) zoneId : zoneId.getRules().getOffset( Instant.now() );
  }
  return offset;
}

代码示例来源:origin: prestodb/presto

@Test
  public void testDateToTimestampCoercion()
  {
    // allow running tests with a connector that supports TIMESTAMP but not DATE

    // ordinary date
    MaterializedResult rows = h2QueryRunner.execute(TEST_SESSION, "SELECT DATE '2018-01-13'", ImmutableList.of(TIMESTAMP));
    assertEquals(rows.getOnlyValue(), LocalDate.of(2018, 1, 13).atStartOfDay());

    // date, which midnight was skipped in JVM zone
    LocalDate forwardOffsetChangeAtMidnightInJvmZone = LocalDate.of(1970, 1, 1);
    checkState(ZoneId.systemDefault().getRules().getValidOffsets(forwardOffsetChangeAtMidnightInJvmZone.atStartOfDay()).size() == 0, "This test assumes certain JVM time zone");
    rows = h2QueryRunner.execute(TEST_SESSION, DateTimeFormatter.ofPattern("'SELECT DATE '''uuuu-MM-dd''").format(forwardOffsetChangeAtMidnightInJvmZone), ImmutableList.of(TIMESTAMP));
    assertEquals(rows.getOnlyValue(), forwardOffsetChangeAtMidnightInJvmZone.atStartOfDay());
  }
}

代码示例来源:origin: wildfly/wildfly

assertTrue(immutability.test(YearMonth.now()));
assertTrue(immutability.test(ZoneOffset.UTC));
assertTrue(immutability.test(ZoneRules.of(ZoneOffset.UTC).nextTransition(Instant.now())));
assertTrue(immutability.test(ZoneOffsetTransitionRule.of(Month.JANUARY, 1, DayOfWeek.SUNDAY, LocalTime.MIDNIGHT, true, TimeDefinition.STANDARD, ZoneOffset.UTC, ZoneOffset.ofHours(1), ZoneOffset.ofHours(2))));
assertTrue(immutability.test(ZoneRules.of(ZoneOffset.UTC)));
assertTrue(immutability.test(ZonedDateTime.now()));
assertTrue(immutability.test(new JCIPImmutableObject()));

代码示例来源:origin: com.github.seratch/java-time-backport

/**
 * 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: jpos/jPOS

public void exec(CLIContext cli, String[] args) throws Exception
  {
    ZoneId zi = ZoneId.systemDefault();
    Instant i = Instant.now();
    cli.println(
      "         Zone ID: " + zi + " (" + zi.getDisplayName(TextStyle.FULL, Locale.getDefault()) + ") "
        + zi.getRules().getOffset(i)
    );
    cli.println ("             UTC: " + i);
    ZoneOffsetTransition tran = zi.getRules().nextTransition(i);
    if (tran != null) {
      Instant in = tran.getInstant();
      cli.println (" Next transition: " + in + " (" + in.atZone(zi) + ")");
    }
    List<ZoneOffsetTransitionRule> l = zi.getRules().getTransitionRules();
    for (ZoneOffsetTransitionRule r : l) {
      cli.println (" Transition rule: " + r);
    }
  }
}

代码示例来源:origin: net.time4j/time4j-olson

ZonalOffset initialOffset = ZonalOffset.ofTotalSeconds(zoneRules.getOffset(Instant.MIN).getTotalSeconds());
List<ZonalTransition> transitions = new ArrayList<>();
List<DaylightSavingRule> rules = new ArrayList<>();
for (ZoneOffsetTransition zot : zoneRules.getTransitions()) {
  Instant instant = zot.getInstant();
  long posixTime = instant.getEpochSecond();
  int previousOffset = zot.getOffsetBefore().getTotalSeconds();
  int totalOffset = zot.getOffsetAfter().getTotalSeconds();
  int dst = Math.toIntExact(zoneRules.getDaylightSavings(instant).getSeconds());
  transitions.add(new ZonalTransition(posixTime, previousOffset, totalOffset, dst));
for (ZoneOffsetTransitionRule zotr : zoneRules.getTransitionRules()) {
  DaylightSavingRule rule;

代码示例来源:origin: com.github.seratch/java-time-backport

List<ZoneOffset> validOffsets = rules.getValidOffsets(isoLDT);
ZoneOffset offset;
if (validOffsets.size() == 1) {
  offset = validOffsets.get(0);
} else if (validOffsets.size() == 0) {
  ZoneOffsetTransition trans = rules.getTransition(isoLDT);
  localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());
  offset = trans.getOffsetAfter();

代码示例来源:origin: stackoverflow.com

ZoneId zoneId = ZoneId.of("Australia/Sydney");
ZoneRules rules = zoneId.getRules();

ZoneOffsetTransition nextTransition = rules.nextTransition(Instant.now());
System.out.println("Next transition at: " +
    nextTransition.getInstant().atZone(zoneId));

ZoneOffsetTransition nextNextTransition =
    rules.nextTransition(nextTransition.getInstant());
System.out.println("Next transition after that at: " +
    nextNextTransition.getInstant().atZone(zoneId));

代码示例来源:origin: org.onehippo.cms7/hippo-cms-api

private boolean isDST() {
    return zoneId.getRules().isDaylightSavings(instant);
  }
}

代码示例来源:origin: ical4j/ical4j

private static void addTransitionRules(ZoneId zoneId, int rawTimeZoneOffsetInSeconds, VTimeZone result) {
  ZoneOffsetTransition zoneOffsetTransition = null;
  if (!zoneId.getRules().getTransitions().isEmpty()) {
    Collections.min(zoneId.getRules().getTransitions(),
        Comparator.comparing(ZoneOffsetTransition::getDateTimeBefore));
  for (ZoneOffsetTransitionRule transitionRule : zoneId.getRules().getTransitionRules()) {
    int transitionRuleMonthValue = transitionRule.getMonth().getValue();
    DayOfWeek transitionRuleDayOfWeek = transitionRule.getDayOfWeek();

代码示例来源:origin: infiniteautomation/ma-core-public

/**
   * @param zdt
   * @return
   */
  public Instant getInstant(ZonedDateTime zdt) {
    ZonedDateTime offset = zdt.withHour(hour).withMinute(minute).withSecond(second).withNano((int)(millisecond * 1000000l));
    LocalDateTime ldt = zdt.toLocalDateTime();
    ldt = ldt.withHour(hour).withMinute(minute).withSecond(second).withNano((int)(millisecond * 1000000l));
    
    if(!zdt.getZone().getRules().isValidOffset(ldt, zdt.getOffset())) {
      //Within a gap of DST so OR after the transition
      ZoneOffsetTransition transition = zdt.getZone().getRules().nextTransition(zdt.toInstant());
      if(!ldt.isAfter(transition.getDateTimeAfter())){
        //In a gap so we shift our time forward to the end of the gap.
        offset = transition.getDateTimeAfter().atZone(zdt.getZone());
      }else {
        //After a gap so ensure we use the next zone offset
        offset = ldt.atOffset(transition.getOffsetAfter()).atZoneSimilarLocal(transition.getOffsetAfter());
      }
    }
    
    return offset.toInstant();
  }
}

代码示例来源:origin: com.helger/ph-oton-bootstrap3-pages

final ZoneOffset aZO = aZR.getOffset (aNow);
aRow.addCell (aDTZ.getDisplayName (TextStyle.SHORT, aDisplayLocale));
aRow.addCell (Duration.ofSeconds (aZO.getTotalSeconds ()).toString ());
aRow.addCell (EPhotonCoreText.getYesOrNo (aZR.isFixedOffset (), aDisplayLocale));

代码示例来源:origin: jpos/jPOS

p.printf("%s     timezone: %s (%s) %s%n", indent, zi,
    zi.getDisplayName(TextStyle.FULL, Locale.getDefault()),
    zi.getRules().getOffset(instant).toString());
p.printf("%swatch service: %s%n", indent, getServer().getWatchServiceClassname());
List<ZoneOffsetTransitionRule> l = zi.getRules().getTransitionRules();
for (ZoneOffsetTransitionRule tr : l) {
  p.printf("%s         rule: %s%n", indent, tr.toString());
ZoneOffsetTransition tran = zi.getRules().nextTransition(instant);
if (tran != null) {
  Instant in = tran.getInstant();

代码示例来源:origin: com.github.seratch/java-time-backport

List<ZoneOffset> validOffsets = rules.getValidOffsets(localDateTime);
ZoneOffset offset;
if (validOffsets.size() == 1) {
  offset = validOffsets.get(0);
} else if (validOffsets.size() == 0) {
  ZoneOffsetTransition trans = rules.getTransition(localDateTime);
  localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());
  offset = trans.getOffsetAfter();

代码示例来源:origin: com.vaadin/vaadin-server

while (true) {
  ZoneOffsetTransition t = rules
      .nextTransition(i.toInstant());
  if (t == null) {
    break;

代码示例来源:origin: kousen/java_8_recipes

public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
    List<ZonedDateTime> antarticZones =
        ZoneId.getAvailableZoneIds().stream()  // Stream<String>
            .filter(regionId -> regionId.contains("Antarctica"))
            .map(ZoneId::of)  // Stream<ZoneId>
            .map(now::atZone) // Stream<ZonedDateTime>
            .sorted(comparingInt(zoneId -> zoneId.getOffset().getTotalSeconds()))
            .collect(Collectors.toList());

    antarticZones.forEach(zdt ->
        System.out.printf("%7s: %25s %7s%n", zdt.getOffset(), zdt.getZone(),
            zdt.getZone().getRules().isDaylightSavings(zdt.toInstant())));
  }
}

代码示例来源:origin: org.mnode.ical4j/ical4j

private static void addTransitionRules(ZoneId zoneId, int rawTimeZoneOffsetInSeconds, VTimeZone result) {
  ZoneOffsetTransition zoneOffsetTransition = null;
  if (!zoneId.getRules().getTransitions().isEmpty()) {
    Collections.min(zoneId.getRules().getTransitions(),
        Comparator.comparing(ZoneOffsetTransition::getDateTimeBefore));
  for (ZoneOffsetTransitionRule transitionRule : zoneId.getRules().getTransitionRules()) {
    int transitionRuleMonthValue = transitionRule.getMonth().getValue();
    DayOfWeek transitionRuleDayOfWeek = transitionRule.getDayOfWeek();

代码示例来源:origin: Graylog2/graylog2-server

final LocalDateTime localDateTime = (LocalDateTime) value;
  final ZoneId defaultZoneId = ZoneId.systemDefault();
  final ZoneOffset offset = defaultZoneId.getRules().getOffset(localDateTime);
  date = Date.from(localDateTime.toInstant(offset));
} else if (value instanceof LocalDate) {
  final LocalDateTime localDateTime = localDate.atStartOfDay();
  final ZoneId defaultZoneId = ZoneId.systemDefault();
  final ZoneOffset offset = defaultZoneId.getRules().getOffset(localDateTime);
  date = Date.from(localDateTime.toInstant(offset));
} else if (value instanceof Instant) {

代码示例来源:origin: com.helger/ph-oton-bootstrap4-pages

final ZoneOffset aZO = aZR.getOffset (aNow);
aRow.addCell (aDTZ.getDisplayName (TextStyle.SHORT, aDisplayLocale));
aRow.addCell (Duration.ofSeconds (aZO.getTotalSeconds ()).toString ());
aRow.addCell (EPhotonCoreText.getYesOrNo (aZR.isFixedOffset (), aDisplayLocale));

代码示例来源:origin: prestodb/presto

@Test
  public void testLocallyUnrepresentableTimeLiterals()
  {
    LocalDateTime localTimeThatDidNotExist = LocalDateTime.of(2017, 4, 2, 2, 10);
    checkState(ZoneId.systemDefault().getRules().getValidOffsets(localTimeThatDidNotExist).isEmpty(), "This test assumes certain JVM time zone");
    // This tests that both Presto runner and H2 can return TIMESTAMP value that never happened in JVM's zone (e.g. is not representable using java.sql.Timestamp)
    @Language("SQL") String sql = DateTimeFormatter.ofPattern("'SELECT TIMESTAMP '''uuuu-MM-dd HH:mm:ss''").format(localTimeThatDidNotExist);
    assertEquals(computeScalar(sql), localTimeThatDidNotExist); // this tests Presto and the QueryRunner
    assertQuery(sql); // this tests H2QueryRunner

    LocalDate localDateThatDidNotHaveMidnight = LocalDate.of(1970, 1, 1);
    checkState(ZoneId.systemDefault().getRules().getValidOffsets(localDateThatDidNotHaveMidnight.atStartOfDay()).isEmpty(), "This test assumes certain JVM time zone");
    // This tests that both Presto runner and H2 can return DATE value for a day which midnight never happened in JVM's zone (e.g. is not exactly representable using java.sql.Date)
    sql = DateTimeFormatter.ofPattern("'SELECT DATE '''uuuu-MM-dd''").format(localDateThatDidNotHaveMidnight);
    assertEquals(computeScalar(sql), localDateThatDidNotHaveMidnight); // this tests Presto and the QueryRunner
    assertQuery(sql); // this tests H2QueryRunner

    LocalTime localTimeThatDidNotOccurOn19700101 = LocalTime.of(0, 10);
    checkState(ZoneId.systemDefault().getRules().getValidOffsets(localTimeThatDidNotOccurOn19700101.atDate(LocalDate.ofEpochDay(0))).isEmpty(), "This test assumes certain JVM time zone");
    checkState(!Objects.equals(java.sql.Time.valueOf(localTimeThatDidNotOccurOn19700101).toLocalTime(), localTimeThatDidNotOccurOn19700101), "This test assumes certain JVM time zone");
    sql = DateTimeFormatter.ofPattern("'SELECT TIME '''HH:mm:ss''").format(localTimeThatDidNotOccurOn19700101);
    assertEquals(computeScalar(sql), localTimeThatDidNotOccurOn19700101); // this tests Presto and the QueryRunner
    assertQuery(sql); // this tests H2QueryRunner
  }
}

相关文章