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

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

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

Year介绍

[英]A year in the ISO-8601 calendar system, such as 2007.

Year is an immutable date-time object that represents a year. Any field that can be derived from a year can be obtained.

Note that years in the ISO chronology only align with years in the Gregorian-Julian system for modern years. Parts of Russia did not switch to the modern Gregorian/ISO rules until 1920. As such, historical years must be treated with caution.

This class does not store or represent a month, day, time or time-zone. For example, the value "2007" can be stored in a Year.

Years represented by this class follow the ISO-8601 standard and use the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.

The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today's rules for leap years are applied for all time. For most applications written today, the ISO-8601 rules are entirely suitable. However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable.

Specification for implementors

This class is immutable and thread-safe.
[中]ISO-8601日历系统中的一年,如2007年。
Year是表示年份的不可变日期时间对象。可以从一年中得到任何字段。
请注意,ISO年表中的年份仅与现代格里高利-朱利安体系中的年份一致。直到1920年,俄罗斯部分地区才改用现代的格里高利/ISO规则。因此,必须谨慎对待历史年份。
此类不存储或表示月、日、时间或时区。例如,值“2007”可以存储在一年内。
该类别所代表的年份遵循ISO-8601标准,并使用proleptic编号系统。第一年之前是第0年,然后是第1年。
ISO-8601日历系统是当今世界大部分地区使用的现代民用日历系统。它相当于公历的前身,即今天的闰年规则一直适用。对于今天编写的大多数应用程序,ISO-8601规则完全适用。然而,任何使用历史日期并要求其准确的应用程序都会发现ISO-8601方法不合适。
####实施者规范
这个类是不可变的,是线程安全的。

代码示例

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

/**
 * Converts a MySQL {@code YEAR} value to a {@link Year} object.
 *
 * @param inputStream the binary stream containing the raw binlog event data for the value
 * @return the {@link Year} object
 * @throws IOException if there is an error reading from the binlog event data
 */
protected static Serializable deserializeYear(ByteArrayInputStream inputStream) throws IOException {
  return Year.of(1900 + inputStream.readInteger(1));
}

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

@Override
public void serialize(Year year, JsonGenerator generator, SerializerProvider provider) throws IOException
{
  if (useTimestamp(provider)) {
    generator.writeNumber(year.getValue());
  } else {
    String str = (_formatter == null) ? year.toString() : year.format(_formatter);
    generator.writeString(str);
  }
}

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

@Override
  public Year deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    if (formatter == null) {
      return Year.of(parser.getValueAsInt());
    }
    return Year.parse(parser.getValueAsString(), formatter);
  }
}

代码示例来源:origin: kiegroup/optaplanner

@Test(expected = IllegalArgumentException.class)
public void remainderOnIncrementTypeExceedsMaximumYear() {
  Year from = Year.of(Year.MIN_VALUE);
  Year to = Year.of(Year.MAX_VALUE - 0);
  assertNotEquals(0, (to.getValue() - from.getValue()) % 10); // Maximum Year range is not divisible by 10
  assertNotNull(new TemporalValueRange<>(from, to, 1, ChronoUnit.DECADES));
}

代码示例来源:origin: apache/metron

@SuppressWarnings("rawtypes")
 @Test
 public void testTimestampParsing() throws ParseException {
  JSONObject parsed = parser.parse(fireeyeMessage.getBytes()).get(0);
  JSONParser parser = new JSONParser();
  Map json = (Map) parser.parse(parsed.toJSONString());
  long expectedTimestamp = ZonedDateTime.of(Year.now(ZoneOffset.UTC).getValue(), 3, 19, 5, 24, 39, 0, ZoneOffset.UTC).toInstant().toEpochMilli();
  Assert.assertEquals(expectedTimestamp, json.get("timestamp"));
 }
}

代码示例来源:origin: com.thoughtworks.xstream/xstream

return GregorianCalendar.from(ot.atDate(LocalDate.ofEpochDay(0)).atZoneSameInstant(ZoneId.systemDefault()));
} catch (final DateTimeParseException e) {
  return GregorianCalendar.from(ot.atDate(LocalDate.ofEpochDay(0)).atZoneSameInstant(ZoneId.systemDefault()));
} catch (final DateTimeParseException e) {
  final Year y = Year.from(ta);
  final MonthDay md = MonthDay.from(ta);
  final OffsetTime ot = OffsetTime.from(ta);
  return GregorianCalendar.from(ot.atDate(y.atMonthDay(md)).atZoneSameInstant(ZoneId.systemDefault()));
} catch (final DateTimeParseException e) {
  final Year y = Year.from(ta);
  final MonthDay md = MonthDay.from(ta);
  final OffsetTime ot = OffsetTime.from(ta);
  return GregorianCalendar.from(ot.atDate(y.atMonthDay(md)).atZoneSameInstant(ZoneId.systemDefault()));
} catch (final DateTimeParseException e) {
  final Year y = Year.from(ta);
  final MonthDay md = MonthDay.from(ta);
  return GregorianCalendar.from(y.atMonthDay(md).atStartOfDay(ZoneId.systemDefault()));
} catch (final DateTimeParseException e) {
  final Year y = Year.parse(str);
  return GregorianCalendar.from(y.atDay(1).atStartOfDay(ZoneId.systemDefault()));
} catch (final DateTimeParseException e) {

代码示例来源: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(ValueRange.of(0L, 10L)));
assertTrue(immutability.test(WeekFields.ISO));
assertTrue(immutability.test(Year.now()));
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: zsoltherpai/fluent-jdbc

private static void javaTime(Map<Class, ParamSetter> ss) {
  reg(ss, Instant.class, (param, ps, i) -> ps.setTimestamp(i, timestamp(param)));
  reg(ss, OffsetDateTime.class, (param, ps, i) -> ps.setTimestamp(i, timestamp(param.toInstant())));
  reg(ss, ZonedDateTime.class, (param, ps, i) -> ps.setTimestamp(i, timestamp(param.toInstant())));
  reg(ss, LocalDate.class, (param, ps, i) -> ps.setDate(i, java.sql.Date.valueOf(param)));
  reg(ss, LocalTime.class, (param, ps, i) -> ps.setTime(i, java.sql.Time.valueOf(param)));
  reg(ss, LocalDateTime.class, (param, ps, i) -> ps.setTimestamp(i, java.sql.Timestamp.valueOf(param)));
  reg(ss, Year.class, (param, ps, i) -> ps.setDate(i, java.sql.Date.valueOf(LocalDate.of(param.getValue(), Month.JANUARY, 1))));
  reg(ss, YearMonth.class, (param, ps, i) -> ps.setDate(i, java.sql.Date.valueOf(LocalDate.of(param.getYear(), param.getMonth(), 1))));
}

代码示例来源:origin: no.ssb.vtl/java-vtl-model

@Override
  public Instant get() {
    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern("yyyy");
    Year year = Year.parse(input, formatter);
    return year.atDay(1).atStartOfDay(timeZone.toZoneId()).toInstant();
  }
};

代码示例来源:origin: chhsiao90/nitmproxy

public static Certificate newCert(String parentCertFile, String keyFile, String host) {
  try {
    Date before = Date.from(Instant.now());
    Date after = Date.from(Year.now().plus(3, ChronoUnit.YEARS).atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    X509CertificateHolder parent = readPemFromFile(parentCertFile);
    PEMKeyPair pemKeyPair = readPemFromFile(keyFile);
    KeyPair keyPair = new JcaPEMKeyConverter()
        .setProvider(PROVIDER)
        .getKeyPair(pemKeyPair);
    X509v3CertificateBuilder x509 = new JcaX509v3CertificateBuilder(
        parent.getSubject(),
        new BigInteger(64, new SecureRandom()),
        before,
        after,
        new X500Name("CN=" + host),
        keyPair.getPublic());
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
        .build(keyPair.getPrivate());
    JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter()
        .setProvider(PROVIDER);
    return new Certificate(
        keyPair,
        x509CertificateConverter.getCertificate(x509.build(signer)),
        x509CertificateConverter.getCertificate(parent));
  } catch (Exception e) {
    throw new IllegalStateException(e);
  }
}

代码示例来源:origin: arnaudroger/SimpleFlatMapper

@Test
public void testJavaYear() throws Exception {
  java.time.Year value = java.time.Year.now();
  java.time.ZoneId zoneId = ZoneId.of("America/Los_Angeles");
  newFieldMapperAndMapToPS(new ConstantGetter<Object, java.time.Year>(value),  java.time.Year.class, new JavaZoneIdProperty(zoneId));
  newFieldMapperAndMapToPS(NullGetter.<Object,  java.time.Year>getter(), java.time.Year.class);
  verify(ps).setDate(1, new java.sql.Date(value.atMonthDay(MonthDay.of(Month.JANUARY, 1)).atStartOfDay(zoneId).toInstant().toEpochMilli()));
  verify(ps).setNull(2, Types.DATE);
}
//IFJAVA8_END

代码示例来源:origin: thymeleaf/thymeleaf-extras-java8time

Validate.notNull(defaultZoneId, "ZoneId cannot be null");
if (target instanceof Instant) {
  return ZonedDateTime.ofInstant((Instant) target, defaultZoneId);
} else if (target instanceof LocalDate) {
  return ZonedDateTime.of((LocalDate) target, LocalTime.MIDNIGHT, defaultZoneId);
} else if (target instanceof LocalDateTime) {
  return ZonedDateTime.of((LocalDateTime) target, defaultZoneId);
} else if (target instanceof LocalTime) {
  return ZonedDateTime.of(LocalDate.now(), (LocalTime) target, defaultZoneId);
} else if (target instanceof OffsetDateTime) {
  return ((OffsetDateTime) target).toZonedDateTime();
} else if (target instanceof OffsetTime) {
  LocalTime localTime = ((OffsetTime) target).toLocalTime();
  return ZonedDateTime.of(LocalDate.now(), localTime, defaultZoneId);
} else if (target instanceof Year) {
  LocalDate localDate = ((Year) target).atDay(1);
  return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId);
} else if (target instanceof YearMonth) {
  LocalDate localDate = ((YearMonth) target).atDay(1);
  return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId);
} else if (target instanceof ZonedDateTime) {

代码示例来源:origin: apache/tinkerpop

addExtendedEntry(LocalDate.of(2016, 1, 1), "LocalDate", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(LocalDateTime.of(2016, 1, 1, 12, 30), "LocalDateTime", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(LocalTime.of(12, 30, 45), "LocalTime", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(Period.of(1, 6, 15), "Period", "The following example is a `Period` of one year, six months and fifteen days.", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(new Short("100"), "Short", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(Year.of(2016), "Year", "The following example is of the `Year` \"2016\".", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(YearMonth.of(2016, 6), "YearMonth", "The following example is a `YearMonth` of \"June 2016\"", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(ZonedDateTime.of(2016, 12, 23, 12, 12, 24, 36, ZoneId.of("GMT+2")), "ZonedDateTime", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
addExtendedEntry(ZoneOffset.ofHoursMinutesSeconds(3, 6, 9), "ZoneOffset", "The following example is a `ZoneOffset` of three hours, six minutes, and nine seconds.", Compatibilities.UNTYPED_GRAPHSON.matchToArray());

代码示例来源:origin: odrotbohm/spring-restbucks

/**
 * Returns the {@link LocalDate} the {@link CreditCard} expires.
 * 
 * @return will never be {@literal null}.
 */
public LocalDate getExpirationDate() {
  return LocalDate.of(expiryYear.getValue(), expiryMonth, 1);
}

代码示例来源:origin: nl.jqno.equalsverifier/equalsverifier

addValues(SimpleDateFormat.class, new SimpleDateFormat("yMd"), new SimpleDateFormat("dMy"), new SimpleDateFormat("yMd"));
addValues(TimeZone.class, TimeZone.getTimeZone("GMT+1"), TimeZone.getTimeZone("GMT+2"), TimeZone.getTimeZone("GMT+1"));
addValues(Year.class, Year.of(2000), Year.of(2010), Year.of(2000));
addValues(YearMonth.class,
  YearMonth.of(2000, 1),
  YearMonth.of(2010, 12),
  YearMonth.of(2000, 1));
addValues(ZoneId.class, ZoneId.of("+1"), ZoneId.of("-10"), ZoneId.of("+1"));
addValues(ZoneOffset.class, ZoneOffset.ofHours(1), ZoneOffset.ofHours(-1), ZoneOffset.ofHours(1));
addValues(ZonedDateTime.class,
  ZonedDateTime.parse("2017-12-13T10:15:30+01:00"),
  ZonedDateTime.parse("2016-11-12T09:14:29-01:00"),
  ZonedDateTime.parse("2017-12-13T10:15:30+01:00"));

代码示例来源:origin: edu.byu.hbll/time

temporalAccessor = ((LocalDate) temporalAccessor).plusDays(1L);
} else if (temporalAccessor instanceof YearMonth) {
 temporalAccessor = ((YearMonth) temporalAccessor).atDay(1).plusMonths(1L);
} else if (temporalAccessor instanceof Year) {
 temporalAccessor = ((Year) temporalAccessor).atDay(1).plusYears(1L);

代码示例来源:origin: crawler-commons/crawler-commons

LocalDate ldt = null;
if (ta.isSupported(ChronoField.DAY_OF_MONTH)) {
  ldt = LocalDate.from(ta);
} else if (ta.isSupported(ChronoField.MONTH_OF_YEAR)) {
  ldt =  YearMonth.from(ta).atDay(1);
} else if (ta.isSupported(ChronoField.YEAR)) {
  ldt = Year.from(ta).atDay(1);
  return ldt.atStartOfDay(TIME_ZONE_UTC);

代码示例来源:origin: nl.vpro.shared/vpro-shared-xml

@Override
public Temporal unmarshal(String dateValue) {
  if (dateValue == null) {
    return null;
  }
  try {
    return LocalDate.parse(dateValue);
  } catch (DateTimeParseException pe) {
    return Year.parse(dateValue);
  }
}

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

@Test
public void invokeYearLocalDate() {
  FunctionTestUtil.assertResult(
      yamFunction.invoke(LocalDate.of(2017, 6, 12), Year.of(2020)),
      Period.of(2, 6, 0));
}

代码示例来源:origin: edu.byu.hbll/time

temporalAccessor = ((Year) temporalAccessor).atDay(1);
} else if (temporalAccessor instanceof YearMonth) {
 temporalAccessor = ((YearMonth) temporalAccessor).atDay(1);
 temporalAccessor = ((LocalDate) temporalAccessor).atStartOfDay();

相关文章