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

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

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

ZoneOffset介绍

[英]A time-zone offset from Greenwich/UTC, such as +02:00.

A time-zone offset is the period of time that a time-zone differs from Greenwich/UTC. This is usually a fixed number of hours and minutes.

Different parts of the world have different time-zone offsets. The rules for how offsets vary by place and time of year are captured in the ZoneId class.

For example, Paris is one hour ahead of Greenwich/UTC in winter and two hours ahead in summer. The ZoneId instance for Paris will reference two ZoneOffset instances - a +01:00 instance for winter, and a +02:00 instance for summer.

In 2008, time-zone offsets around the world extended from -12:00 to +14:00. To prevent any problems with that range being extended, yet still provide validation, the range of offsets is restricted to -18:00 to 18:00 inclusive.

This class is designed for use with the ISO calendar system. The fields of hours, minutes and seconds make assumptions that are valid for the standard ISO definitions of those fields. This class may be used with other calendar systems providing the definition of the time fields matches those of the ISO calendar system.

Instances of ZoneOffset must be compared using #equals. Implementations may choose to cache certain common offsets, however applications must not rely on such caching.

Specification for implementors

This class is immutable and thread-safe.
[中]与格林威治/UTC的时区偏移,例如+02:00。
时区偏移是时区与格林威治/UTC不同的时间段。这通常是一个固定的小时和分钟数。
世界上不同的地方有不同的时区偏移。ZoneId类中记录了补偿如何随时间和地点变化的规则。
例如,巴黎在冬季比格林威治/UTC早一个小时,在夏季比格林威治/UTC早两个小时。巴黎的ZoneId实例将引用两个ZoneOffset实例——冬季的+01:00实例和夏季的+02:00实例。
2008年,世界各地的时区偏移从-12:00扩展到+14:00。为了防止扩展该范围时出现任何问题,但仍提供验证,偏移范围限制为-18:00到18:00(含18:00)。
本课程设计用于ISO日历系统。小时、分钟和秒字段做出的假设适用于这些字段的标准ISO定义。如果时间字段的定义与ISO日历系统的定义相匹配,则此类可与其他日历系统一起使用。
区域偏移的实例必须使用#equals进行比较。实现可能会选择缓存某些公共偏移量,但是应用程序不能依赖这种缓存。
####实施者规范
这个类是不可变的,是线程安全的。

代码示例

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

@Test
  void shouldGetNanosOfDayUTC()
  {
    LocalTime localTime = LocalTime.of( 14, 19, 18, 123999 );
    ZoneOffset offset = ZoneOffset.ofHours( -12 );
    OffsetTime time = OffsetTime.of( localTime, offset );

    long nanosOfDayUTC = TemporalUtil.getNanosOfDayUTC( time );

    long expectedNanosOfDayUTC = Duration.ofSeconds( localTime.toSecondOfDay() )
        .minus( offset.getTotalSeconds(), SECONDS )
        .toNanos();

    assertEquals( expectedNanosOfDayUTC + localTime.getNano(), nanosOfDayUTC );
  }
}

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

@Override
  protected ZoneOffset deserialize(String key, DeserializationContext ctxt) throws IOException {
    try {
      return ZoneOffset.of(key);
    } catch (DateTimeException e) {
      return _handleDateTimeException(ctxt, ZoneOffset.class, e, key);
    }
  }
}

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

@Override
public Object read( ReadableClosableChannel from ) throws IOException
{
  if ( from.get() == (byte) 0 )
  {
    long epochSecondsUTC = from.getLong();
    int nanos = from.getInt();
    int offsetSeconds = from.getInt();
    return ZonedDateTime.ofInstant( Instant.ofEpochSecond( epochSecondsUTC, nanos ), ZoneOffset.ofTotalSeconds( offsetSeconds ) );
  }
  else
  {
    long epochSecondsUTC = from.getLong();
    int nanos = from.getInt();
    int zoneID = from.getInt();
    String zone = TimeZones.map( (short) zoneID );
    return ZonedDateTime.ofInstant( Instant.ofEpochSecond( epochSecondsUTC, nanos ), ZoneId.of( zone ) );
  }
}

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

public static OffsetTime truncateOffsetToMinutes( OffsetTime value )
{
  int offsetMinutes = value.getOffset().getTotalSeconds() / 60;
  ZoneOffset truncatedOffset = ZoneOffset.ofTotalSeconds( offsetMinutes * 60 );
  return value.withOffsetSameInstant( truncatedOffset );
}

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

private static String currentTimeZoneOffsetString()
  {
    ZoneOffset offset = OffsetDateTime.now().getOffset();
    return offset.equals( UTC ) ? "+0000" : offset.toString().replace( ":", "" );
  }
}

代码示例来源:origin: org.kie/kie-dmn-feel

{ BuiltInType.BOOLEAN, "false", false },
{ BuiltInType.DATE, "2017-07-01", LocalDate.of( 2017, 07, 01 ) },
{ BuiltInType.TIME, "14:32:55", LocalTime.of( 14, 32, 55 ) },
{ BuiltInType.TIME, "14:32:55.125-05:00", OffsetTime.of( 14, 32, 55, 125000000, ZoneOffset.ofHours( -5 ) ) },
{ BuiltInType.TIME, "14:32:55.125Z", OffsetTime.of( 14, 32, 55, 125000000, ZoneOffset.UTC ) },
{ BuiltInType.DATE_TIME, "2017-06-30T10:49:11", LocalDateTime.of( 2017, 06, 30, 10, 49, 11 ) },
{ BuiltInType.DATE_TIME, "2017-06-30T10:49:11.650", LocalDateTime.of( 2017, 06, 30, 10, 49, 11, 650000000 ) },
{ BuiltInType.DATE_TIME, "2017-06-30T10:49:11.650+03:00", ZonedDateTime.of( 2017, 06, 30, 10, 49, 11, 650000000, ZoneOffset.ofHours( 3 ) ) },
{ BuiltInType.DURATION, "P5DT4H23M55S", Duration.ofDays( 5 ).plusHours( 4 ).plusMinutes( 23 ).plusSeconds( 55 ) },
{ BuiltInType.DURATION, "-P5DT4H23M55S", Duration.ofDays( -5 ).minusHours( 4 ).minusMinutes( 23 ).minusSeconds( 55 ) },
{ BuiltInType.DURATION, "P23D", Duration.ofDays( 23 ) },

代码示例来源:origin: kiegroup/droolsjbpm-integration

@Test
public void testMarshallDateObject() {
  String expectedString = "<date-object>\n" +
      "  <localDate>2017-01-01</localDate>\n" +
      "  <localDateTime>2017-01-01T10:10:10</localDateTime>\n" +
      "  <localTime>10:10:10</localTime>\n" +
      "  <offsetDateTime>2017-01-01T10:10:10+01:00</offsetDateTime>\n" +
      "</date-object>";
  Set<Class<?>> extraClasses = new HashSet<Class<?>>();
  extraClasses.add(DateObject.class);
  Marshaller marshaller = MarshallerFactory.getMarshaller( extraClasses, MarshallingFormat.XSTREAM, getClass().getClassLoader() );
  DateObject dateObject = new DateObject();
  dateObject.setLocalDate( LocalDate.of( 2017, 1, 1 ) );
  dateObject.setLocalDateTime( LocalDateTime.of( 2017, 1, 1, 10, 10, 10 ) );
  dateObject.setLocalTime( LocalTime.of( 10, 10, 10 ) );
  dateObject.setOffsetDateTime( OffsetDateTime.of( LocalDateTime.of( 2017, 1, 1, 10, 10, 10 ), ZoneOffset.ofHours( 1 ) ) );
  String dateObjectString = marshaller.marshall( dateObject );
  assertNotNull( dateObjectString );
  assertEquals( expectedString, dateObjectString );
}

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

assertTrue(immutability.test(Duration.ZERO));
assertTrue(immutability.test(Instant.now()));
assertTrue(immutability.test(LocalDate.now()));
assertTrue(immutability.test(LocalDateTime.now()));
assertTrue(immutability.test(LocalTime.now()));
assertTrue(immutability.test(MonthDay.now()));
assertTrue(immutability.test(Period.ZERO));
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: debezium/debezium

LocalDate c1Date = LocalDate.ofEpochDay(c1.getTime() / TimeUnit.DAYS.toMillis(1));
assertThat(c1Date.getYear()).isEqualTo(2014);
assertThat(c1Date.getMonth()).isEqualTo(Month.SEPTEMBER);
assertThat(c1Date.getDayOfMonth()).isEqualTo(8);
LocalTime c2Time = LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(c2.getTime()));
assertThat(c2Time.getHour()).isEqualTo(17);
assertThat(c2Time.getMinute()).isEqualTo(51);
assertThat(c2Time.getSecond()).isEqualTo(4);
assertThat(c2Time.getNano()).isEqualTo((int) TimeUnit.MILLISECONDS.toNanos(780));
long c3Seconds = c3.getTime() / 1000;
long c3Millis = c3.getTime() % 1000;
LocalDateTime c3DateTime = LocalDateTime.ofEpochSecond(c3Seconds,
                            (int) TimeUnit.MILLISECONDS.toNanos(c3Millis),
                            ZoneOffset.UTC);
assertThat(c3DateTime.getYear()).isEqualTo(2014);
assertThat(c3DateTime.getMonth()).isEqualTo(Month.SEPTEMBER);
assertThat(c3DateTime.getDayOfMonth()).isEqualTo(8);
assertThat(c3DateTime.getHour()).isEqualTo(17);
OffsetDateTime c4DateTime = OffsetDateTime.parse(c4, ZonedTimestamp.FORMATTER);
assertThat(c4DateTime.getOffset()).isEqualTo(ZoneOffset.UTC);
c4DateTime = c4DateTime.withOffsetSameInstant(ZoneOffset.of("Z"));
assertThat(c4DateTime.getYear()).isEqualTo(1970);
assertThat(c4DateTime.getMonth()).isEqualTo(Month.JANUARY);

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

private List<InputEntity> randomNodeData()
{
  List<InputEntity> nodes = new ArrayList<>();
  for ( int i = 0; i < 300; i++ )
  {
    InputEntity node = new InputEntity();
    node.id( UUID.randomUUID().toString(), Group.GLOBAL );
    node.property( "name", "Node " + i );
    node.property( "pointA", "\"   { x : -4.2, y : " + i + ", crs: WGS-84 } \"" );
    node.property( "pointB", "\" { x : -8, y : " + i + " } \"" );
    node.property( "date", LocalDate.of( 2018, i % 12 + 1, i % 28 + 1 ) );
    node.property( "time", OffsetTime.of( 1, i % 60, 0, 0, ZoneOffset.ofHours( 9 ) ) );
    node.property( "dateTime",
        ZonedDateTime.of( 2011, 9, 11, 8, i % 60, 0, 0, ZoneId.of( "Europe/Stockholm" ) ) );
    node.property( "dateTime2",
        LocalDateTime.of( 2011, 9, 11, 8, i % 60, 0, 0 ) ); // No zone specified
    node.property( "localTime", LocalTime.of( 1, i % 60, 0 ) );
    node.property( "localDateTime", LocalDateTime.of( 2011, 9, 11, 8, i % 60 ) );
    node.property( "duration", Period.of( 2, -3, i % 30 ) );
    node.labels( randomLabels( random.random() ) );
    nodes.add( node );
  }
  return nodes;
}

代码示例来源:origin: org.eclipse.hawkbit/hawkbit-ui

/**
 * Get list of all time zone offsets supported.
 */
private static List<String> getAllTimeZones() {
  final List<String> lst = ZoneId.getAvailableZoneIds().stream()
      .map(id -> ZonedDateTime.now(ZoneId.of(id)).getOffset().getId().replace("Z", "+00:00")).distinct()
      .collect(Collectors.toList());
  lst.sort(null);
  return lst;
}

代码示例来源:origin: palantir/conjure-java-runtime

@Test
public void testJdk8DateTimeSerialization() throws IOException {
  Duration duration = Duration.ofMinutes(60 * 50 + 1); // 50h, 1min
  assertThat(ser(duration)).isEqualTo("\"PT50H1M\"");
  assertThat(serDe(duration, Duration.class)).isEqualTo(duration);
  OffsetDateTime offsetDateTime = OffsetDateTime.of(2001, 2, 3, 4, 5, 6, 7, ZoneOffset.ofHours(-5));
  assertThat(ser(offsetDateTime)).isEqualTo("\"2001-02-03T04:05:06.000000007-05:00\"");
  assertThat(serDe(offsetDateTime, OffsetDateTime.class)).isEqualTo(offsetDateTime);
  ZonedDateTime zoneDateTime = ZonedDateTime.of(2001, 2, 3, 4, 5, 6, 7, ZoneId.of(ZoneId.SHORT_IDS.get("EST")));
  assertThat(ser(zoneDateTime)).isEqualTo("\"2001-02-03T04:05:06.000000007-05:00\"");
  assertThat(serDe(zoneDateTime, ZonedDateTime.class)).isEqualTo(zoneDateTime);
  LocalDate localDate = LocalDate.of(2001, 2, 3);
  assertThat(ser(localDate)).isEqualTo("\"2001-02-03\"");
  assertThat(serDe(localDate, LocalDate.class)).isEqualTo(localDate);
}

代码示例来源:origin: agrestio/agrest

private static OffsetDateTime fromMillis(long millis) {
    return OffsetDateTime.of(LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()), ZoneOffset.ofHours(3));
  }
}

代码示例来源:origin: neo4j-contrib/neo4j-apoc-procedures

@Test
public void dateParseTest() {
  assertEquals(LocalDate.of(2018,01,01),dateParse("2018/01/01", LocalDate.class, parseList));
  assertEquals(ZonedDateTime.of(2011,01,01,12,0,0,53810000,ZoneOffset.of("+01:00")),dateParse("2011-01-01T12:00:00.05381+01:00", ZonedDateTime.class, parseList));
  assertEquals(LocalDateTime.of(2018,05,10,12,10),dateParse("2018-05-10 12:10", LocalDateTime.class, parseList));
  assertEquals(LocalTime.of(12,10),dateParse("12 10", LocalTime.class, parseList));
  assertEquals(OffsetTime.of(10,15,30,0,ZoneOffset.of("+01:00")),dateParse("10:15:30+01:00", OffsetTime.class, parseList));
}

代码示例来源:origin: com.github.jcustenborder/vertica-stream-writer

@Override
 public void encode(ByteBuffer buffer, OffsetTime input, String name, int size, int scale) {
  OffsetTime midnight = OffsetTime.of(LocalTime.MIDNIGHT, ZoneOffset.UTC);
  OffsetTime utcAdjust = input.withOffsetSameInstant(ZoneOffset.UTC);
  Duration duration = Duration.between(midnight, utcAdjust);
  log.trace("duration= {}", duration.getSeconds());
  log.trace("input = {}", input);
  final long microseconds = TimeUnit.HOURS.toMicros(utcAdjust.getHour()) +
    TimeUnit.MINUTES.toMicros(utcAdjust.getMinute()) +
    TimeUnit.SECONDS.toMicros(utcAdjust.getSecond()) +
    TimeUnit.NANOSECONDS.toMicros(utcAdjust.getNano());

//    final int
  final long offset = TimeUnit.HOURS.toSeconds(24) + input.getOffset().getTotalSeconds(); // ;
  log.trace("microseconds = {} offset = {}", microseconds, offset);
  final long storage = (microseconds << 24) + offset;
  log.trace("storage = {}", storage);
  buffer.putLong(storage);
 }
}

代码示例来源:origin: mulesoft/mule

private void assertEquals(LocalDateTime dateTime, Date date) {
  assertThat(dateTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), equalTo(date.getTime()));
 }
}

代码示例来源:origin: cn.bestwu.simpleframework/simpleframework-web

private long daysOfTwo(Date fDate, Date oDate) {
  LocalDateTime localDate = LocalDateTime
    .ofInstant(Instant.ofEpochMilli(fDate.getTime()), ZoneOffset.of("+8"));
  LocalDateTime localDate2 = LocalDateTime
    .ofInstant(Instant.ofEpochMilli(oDate.getTime()), ZoneOffset
      .of("+8"));
  long days = localDate2.toLocalDate().toEpochDay() - localDate.toLocalDate().toEpochDay();
  return days >= 0 ? days : 0;
 }
}

代码示例来源:origin: org.kie/kie-dmn-feel

public FEELFnResult<TemporalAccessor> invoke(
    @ParameterName("hour") Number hour, @ParameterName("minute") Number minute,
    @ParameterName("second") Number seconds, @ParameterName("offset") Duration offset) {
  if (hour == null) {
    return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "hour", "cannot be null"));
  }
  if (minute == null) {
    return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "minute", "cannot be null"));
  }
  if (seconds == null) {
    return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "seconds", "cannot be null"));
  }
  try {
    int nanosecs = 0;
    if (seconds instanceof BigDecimal) {
      BigDecimal secs = (BigDecimal) seconds;
      nanosecs = secs.subtract(secs.setScale(0, BigDecimal.ROUND_DOWN)).multiply(NANO_MULT).intValue();
    }
    if (offset == null) {
      return FEELFnResult.ofResult(LocalTime.of(hour.intValue(), minute.intValue(), seconds.intValue(),
          nanosecs));
    } else {
      return FEELFnResult.ofResult(OffsetTime.of(hour.intValue(), minute.intValue(), seconds.intValue(),
          nanosecs,
          ZoneOffset.ofTotalSeconds((int) offset.getSeconds())));
    }
  } catch (DateTimeException e) {
    return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "time-parsing exception", e));
  }
}

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

private static ZoneId toZoneId( int z )
{
  // if lowest bit is set to 1 then it's a shifted zone id
  if ( (z & 1) != 0 )
  {
    final String zoneId = TimeZones.map( (short) (z >> 1) );
    return ZoneId.of( zoneId );
  }
  // otherwise it's a shifted offset seconds value
  // preserve sign bit for negative offsets
  return ZoneOffset.ofTotalSeconds( z >> 1 );
}

代码示例来源:origin: ogcs/Okra

public static long parseDate(String date, String pattern, String zone) {
  return LocalDate.parse(date, DateTimeFormatter.ofPattern(pattern))
      .atStartOfDay()
      .toEpochSecond(ZoneOffset.of(zone)) * 1000L;
}

相关文章