类java.time.Period源码实例Demo

下面列出了怎么用java.time.Period的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Strata   文件: RatesCalibrationCsvLoader.java
private static CurveNode curveFixedInflationCurveNode(
    String conventionStr,
    String timeStr,
    String label,
    QuoteId quoteId,
    double spread,
    CurveNodeDate date,
    CurveNodeDateOrder order) {

  Matcher matcher = SIMPLE_YM_TIME_REGEX.matcher(timeStr.toUpperCase(Locale.ENGLISH));
  if (!matcher.matches()) {
    throw new IllegalArgumentException(Messages.format("Invalid time format for Fixed-Inflation swap: {}", timeStr));
  }
  Period periodToEnd = Period.parse("P" + matcher.group(1));
  FixedInflationSwapConvention convention = FixedInflationSwapConvention.of(conventionStr);
  FixedInflationSwapTemplate template = FixedInflationSwapTemplate.of(Tenor.of(periodToEnd), convention);
  return FixedInflationSwapCurveNode.builder()
      .template(template)
      .rateId(quoteId)
      .additionalSpread(spread)
      .label(label)
      .date(date)
      .dateOrder(order)
      .build();
}
 
源代码2 项目: openjdk-jdk9   文件: TCKDateTimeParseResolver.java
@Test(dataProvider="resolveSecondOfDay")
public void test_resolveSecondOfDay(ResolverStyle style, long value, Integer expectedSecond, int expectedDays) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(SECOND_OF_DAY).toFormatter();

    if (expectedSecond != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.ofSecondOfDay(expectedSecond));
        assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
源代码3 项目: Strata   文件: InflationRateCalculationTest.java
@Test
public void test_createRateComputation_Monthly() {
  InflationRateCalculation test = InflationRateCalculation.builder()
      .index(GB_HICP)
      .lag(Period.ofMonths(3))
      .indexCalculationMethod(MONTHLY)
      .firstIndexValue(START_INDEX)
      .build();
  InflationEndMonthRateComputation obs1 = InflationEndMonthRateComputation.of(
      GB_HICP, START_INDEX, YearMonth.from(DATE_2015_02_05).minusMonths(3));
  InflationEndMonthRateComputation obs2 = InflationEndMonthRateComputation.of(
      GB_HICP, START_INDEX, YearMonth.from(DATE_2015_03_07).minusMonths(3));
  InflationEndMonthRateComputation obs3 = InflationEndMonthRateComputation.of(
      GB_HICP, START_INDEX, YearMonth.from(DATE_2015_04_05).minusMonths(3));
  assertThat(test.createRateComputation(DATE_2015_02_05)).isEqualTo(obs1);
  assertThat(test.createRateComputation(DATE_2015_03_07)).isEqualTo(obs2);
  assertThat(test.createRateComputation(DATE_2015_04_05)).isEqualTo(obs3);
}
 
@Test
public void test_filtered_dropOther_atEnd() {
  DummyFraCurveNode node1 = DummyFraCurveNode.of(Period.ofDays(5), GBP_LIBOR_1M, TICKER);
  DummyFraCurveNode node2 = DummyFraCurveNode.of(Period.ofDays(10), GBP_LIBOR_1M, TICKER);
  DummyFraCurveNode node3 = DummyFraCurveNode.of(Period.ofDays(11), GBP_LIBOR_1M, TICKER, DROP_OTHER_2D);
  ImmutableList<DummyFraCurveNode> nodes = ImmutableList.of(node1, node2, node3);

  InterpolatedNodalCurveDefinition test = InterpolatedNodalCurveDefinition.builder()
      .name(CURVE_NAME)
      .xValueType(ValueType.YEAR_FRACTION)
      .yValueType(ValueType.ZERO_RATE)
      .dayCount(ACT_365F)
      .nodes(nodes)
      .interpolator(CurveInterpolators.LINEAR)
      .extrapolatorLeft(CurveExtrapolators.FLAT)
      .extrapolatorRight(CurveExtrapolators.FLAT)
      .build();
  assertThat(test.filtered(VAL_DATE, REF_DATA).getNodes()).containsExactly(node1, node3);
}
 
源代码5 项目: openjdk-jdk9   文件: TCKDateTimeParseResolver.java
@Test(dataProvider="resolveFourToTime")
public void test_resolveFourToDateTime(ResolverStyle style,
                   long hour, long min, long sec, long nano, LocalTime expectedTime, Period excessPeriod) {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .parseDefaulting(YEAR, 2012).parseDefaulting(MONTH_OF_YEAR, 6).parseDefaulting(DAY_OF_MONTH, 30)
            .parseDefaulting(HOUR_OF_DAY, hour)
            .parseDefaulting(MINUTE_OF_HOUR, min)
            .parseDefaulting(SECOND_OF_MINUTE, sec)
            .parseDefaulting(NANO_OF_SECOND, nano).toFormatter();

    ResolverStyle[] styles = (style != null ? new ResolverStyle[] {style} : ResolverStyle.values());
    if (expectedTime != null && excessPeriod != null) {
        LocalDate expectedDate = LocalDate.of(2012, 6, 30).plus(excessPeriod);
        for (ResolverStyle s : styles) {
            TemporalAccessor accessor = f.withResolverStyle(s).parse("");
            assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate, "ResolverStyle: " + s);
            assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime, "ResolverStyle: " + s);
            assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ZERO, "ResolverStyle: " + s);
        }
    }
}
 
@Test
public void test_filtered_dropOther_middle() {
  DummyFraCurveNode node1 = DummyFraCurveNode.of(Period.ofDays(3), GBP_LIBOR_1M, TICKER);
  DummyFraCurveNode node2 = DummyFraCurveNode.of(Period.ofDays(4), GBP_LIBOR_1M, TICKER, DROP_OTHER_2D);
  DummyFraCurveNode node3 = DummyFraCurveNode.of(Period.ofDays(11), GBP_LIBOR_1M, TICKER);
  ImmutableList<DummyFraCurveNode> nodes = ImmutableList.of(node1, node2, node3);

  InterpolatedNodalCurveDefinition test = InterpolatedNodalCurveDefinition.builder()
      .name(CURVE_NAME)
      .xValueType(ValueType.YEAR_FRACTION)
      .yValueType(ValueType.ZERO_RATE)
      .dayCount(ACT_365F)
      .nodes(nodes)
      .interpolator(CurveInterpolators.LINEAR)
      .extrapolatorLeft(CurveExtrapolators.FLAT)
      .extrapolatorRight(CurveExtrapolators.FLAT)
      .build();
  assertThat(test.filtered(VAL_DATE, REF_DATA).getNodes()).containsExactly(node2, node3);
}
 
源代码7 项目: jdk8u-dev-jdk   文件: TCKDateTimeParseResolver.java
@Test(dataProvider="resolveSecondOfDay")
public void test_resolveSecondOfDay(ResolverStyle style, long value, Integer expectedSecond, int expectedDays) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(SECOND_OF_DAY).toFormatter();

    if (expectedSecond != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.ofSecondOfDay(expectedSecond));
        assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
@Test
public void whenAdjust_thenFourteenDaysAfterDate() {
    LocalDate localDate = LocalDate.of(2017, 07, 8);
    TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14));
    LocalDate result = localDate.with(temporalAdjuster);

    String fourteenDaysAfterDate = "2017-07-22";

    assertEquals(fourteenDaysAfterDate, result.toString());
}
 
源代码9 项目: jdk8u-jdk   文件: TCKYear.java
@DataProvider(name="plusInvalidUnit")
Object[][] data_plusInvalidUnit() {
    return new Object[][] {
            {Period.of(0, 1, 0)},
            {Period.of(0, 0, 1)},
            {Period.of(0, 1, 1)},
            {Period.of(1, 1, 1)},
            {Duration.ofDays(1)},
            {Duration.ofHours(1)},
            {Duration.ofMinutes(1)},
            {Duration.ofSeconds(1)},
    };
}
 
源代码10 项目: armeria   文件: AnnotatedValueResolverTest.java
void time(@Param @Default("PT20.345S") Duration duration,
@Param @Default("2007-12-03T10:15:30.00Z") Instant instant,
@Param @Default("2007-12-03") LocalDate localDate,
@Param @Default("2007-12-03T10:15:30") LocalDateTime localDateTime,
@Param @Default("10:15") LocalTime localTime,
@Param @Default("2007-12-03T10:15:30+01:00") OffsetDateTime offsetDateTime,
@Param @Default("10:15:30+01:00") OffsetTime offsetTime,
@Param @Default("P1Y2M3W4D") Period period,
@Param @Default("2007-12-03T10:15:30+01:00[Europe/Paris]") ZonedDateTime zonedDateTime,
@Param @Default("America/New_York") ZoneId zoneId,
@Param @Default("+01:00:00") ZoneOffset zoneOffset) {}
 
源代码11 项目: openjdk-8-source   文件: TCKYear.java
@DataProvider(name="plusInvalidUnit")
Object[][] data_plusInvalidUnit() {
    return new Object[][] {
            {Period.of(0, 1, 0)},
            {Period.of(0, 0, 1)},
            {Period.of(0, 1, 1)},
            {Period.of(1, 1, 1)},
            {Duration.ofDays(1)},
            {Duration.ofHours(1)},
            {Duration.ofMinutes(1)},
            {Duration.ofSeconds(1)},
    };
}
 
源代码12 项目: openjdk-jdk8u   文件: TCKChronoPeriod.java
@Test(dataProvider="calendars")
public void test_toString(Chronology chrono) {
    ChronoPeriod period = chrono.period(1, 2, 3);
    if (period instanceof Period == false) {
        assertEquals(period.toString(), chrono.getId() + " P1Y2M3D");
    }
}
 
@Test
public void changeAfterRuleSegmentsFinish() {
    final List<ValueGroupChange> changes = getValueGroupChanges(new DateRange(NOW.plus(Period.ofWeeks(10)),
            NOW.plus(Period.ofWeeks(12))), Arrays.asList("CME", "CBOT", "CBOT"), false);
    assertEquals(4, changes.size());

    this.builder = RuleGroupChangeBuilder.creator(changes, this.ruleSet);
    final List<RuleChange> ruleChanges = this.builder.build();
    assertEquals(6, ruleChanges.size());

    final List<RuleChange> originals = RuleChangeBuilderTest.getChangesByType(ruleChanges, Type.ORIGINAL);
    assertEquals(3, originals.size());

    assertOriginalSegmentsRemoved(originals);

    final List<RuleChange> newChanges = RuleChangeBuilderTest.getChangesByType(ruleChanges, Type.NEW);
    assertEquals(3, newChanges.size());

    assertRuleChange(newChanges.get(0), Type.NEW, null, new UUID(0, 2),
            new String[]{"VOICE", GroupDriver.VG_PREFIX + getUuid(changes, 1), "ED", "US", "INDEX"},
            Collections.singletonMap("Rate1", "1.1 "),
            NOW.plus(Period.ofWeeks(2)), NOW.plus(Period.ofWeeks(4)));

    assertRuleChange(newChanges.get(1), Type.NEW, null, new UUID(0, 2),
            new String[]{"EMAIL", GroupDriver.VG_PREFIX + getUuid(changes, 1), "ED", "US", "INDEX"},
            Collections.singletonMap("Rate1", "1.2"),
            NOW.plus(Period.ofWeeks(4)), NOW.plus(Period.ofWeeks(6)));

    assertRuleChange(newChanges.get(2), Type.NEW, null, new UUID(0, 2),
            new String[]{"ELECTRONIC", GroupDriver.VG_PREFIX + getUuid(changes, 1), "ED", "US", "INDEX"},
            Collections.singletonMap("Rate1", "1.3"),
            NOW.plus(Period.ofWeeks(6)), NOW.plus(Period.ofWeeks(8)));
}
 
源代码14 项目: jdk8u60   文件: TCKPeriod.java
@Test
public void factory_of_ints() {
    assertPeriod(Period.of(1, 2, 3), 1, 2, 3);
    assertPeriod(Period.of(0, 2, 3), 0, 2, 3);
    assertPeriod(Period.of(1, 0, 0), 1, 0, 0);
    assertPeriod(Period.of(0, 0, 0), 0, 0, 0);
    assertPeriod(Period.of(-1, -2, -3), -1, -2, -3);
}
 
源代码15 项目: jdk8u-jdk   文件: TCKInstantPrinterParser.java
@Test
public void test_parse_leapSecond() {
    Instant expected = OffsetDateTime.of(1970, 2, 3, 23, 59, 59, 123456789, ZoneOffset.UTC).toInstant();
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(-1).toFormatter();
    for (ResolverStyle style : ResolverStyle.values()) {
        TemporalAccessor parsed = f.withResolverStyle(style).parse("1970-02-03T23:59:60.123456789Z");
        assertEquals(parsed.query(Instant::from), expected);
        assertEquals(parsed.query(DateTimeFormatter.parsedExcessDays()), Period.ZERO);
        assertEquals(parsed.query(DateTimeFormatter.parsedLeapSecond()), Boolean.TRUE);
    }
}
 
源代码16 项目: yago3   文件: AgeExtractor.java
/** Calculate the difference between two dates in years */
private static int yearsDiff(String start, String end) {
  LocalDate startDate = yagoToDate(start).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
  LocalDate endDate = yagoToDate(end).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

  Period p = Period.between(startDate, endDate);
  return p.getYears();
}
 
源代码17 项目: jdk8u-jdk   文件: TCKPeriod.java
@Test
public void test_minusDays() {
    assertPeriod(Period.of(1, 2, 3).minusDays(0), 1, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minusDays(10), 1, 2, -7);
    assertPeriod(Period.of(1, 2, 3).minusDays(-10), 1, 2, 13);
    assertPeriod(Period.of(1, 2, 3).minusDays(-3), 1, 2, 6);

    assertPeriod(Period.of(1, 2, 3).minus(Period.ofDays(0)), 1, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minus(Period.ofDays(10)), 1, 2, -7);
    assertPeriod(Period.of(1, 2, 3).minus(Period.ofDays(-10)), 1, 2, 13);
    assertPeriod(Period.of(1, 2, 3).minus(Period.ofDays(-3)), 1, 2, 6);
}
 
源代码18 项目: openjdk-8-source   文件: TCKPeriod.java
public void test_hashCode() {
    Period test5 = Period.ofDays(5);
    Period test6 = Period.ofDays(6);
    Period test5M = Period.ofMonths(5);
    Period test5Y = Period.ofYears(5);
    assertEquals(test5.hashCode() == test5.hashCode(), true);
    assertEquals(test5.hashCode() == test6.hashCode(), false);
}
 
源代码19 项目: jdk8u60   文件: Parsed.java
private void updateCheckConflict(LocalTime timeToSet, Period periodToSet) {
    if (time != null) {
        if (time.equals(timeToSet) == false) {
            throw new DateTimeException("Conflict found: Fields resolved to different times: " + time + " " + timeToSet);
        }
        if (excessDays.isZero() == false && periodToSet.isZero() == false && excessDays.equals(periodToSet) == false) {
            throw new DateTimeException("Conflict found: Fields resolved to different excess periods: " + excessDays + " " + periodToSet);
        } else {
            excessDays = periodToSet;
        }
    } else {
        time = timeToSet;
        excessDays = periodToSet;
    }
}
 
源代码20 项目: alibaba-rsocket-broker   文件: PeriodSerializer.java
@Override
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
    if (obj == null) {
        out.writeNull();
    } else {
        out.writeObject(new PeriodHandle((Period) obj));
    }
}
 
源代码21 项目: hottub   文件: TCKPeriod.java
@Test
public void test_plusYears() {
    assertPeriod(Period.of(1, 2, 3).plusYears(0), 1, 2, 3);
    assertPeriod(Period.of(1, 2, 3).plusYears(10), 11, 2, 3);
    assertPeriod(Period.of(1, 2, 3).plusYears(-10), -9, 2, 3);
    assertPeriod(Period.of(1, 2, 3).plusYears(-1), 0, 2, 3);

    assertPeriod(Period.of(1, 2, 3).plus(Period.ofYears(0)), 1, 2, 3);
    assertPeriod(Period.of(1, 2, 3).plus(Period.ofYears(10)), 11, 2, 3);
    assertPeriod(Period.of(1, 2, 3).plus(Period.ofYears(-10)), -9, 2, 3);
    assertPeriod(Period.of(1, 2, 3).plus(Period.ofYears(-1)), 0, 2, 3);
}
 
@Test
public void amendsFirstSegmentToFinishAfterLastRuleSegment() {
    createBuilder(new UUID(0, 1), new DateRange(NOW.plus(Period.ofWeeks(1)), NOW.plus(Period.ofWeeks(9))));
    final List<RuleChange> changes = this.builder.build();
    assertThat(changes, hasSize(4));

    final List<RuleChange> originals = getChangesByType(changes, Type.ORIGINAL);
    assertThat(originals, hasSize(3));

    assertRuleChange(originals.get(0), Type.ORIGINAL, new UUID(0, 1), new UUID(0, 2),
            new String[]{"VOICE", "CME", "ED", "US", "INDEX"}, Collections.singletonMap("Rate", "1.1"),
            NOW.plus(Period.ofWeeks(2)), NOW.plus(Period.ofWeeks(4)).minusMillis(1L));

    assertRuleChange(originals.get(1), Type.ORIGINAL, new UUID(0, 2), new UUID(0, 2),
            new String[]{"EMAIL", "CME", "ED", "US", "INDEX"}, Collections.singletonMap("Rate", "1.2"),
            NOW.plus(Period.ofWeeks(4)), NOW.plus(Period.ofWeeks(6)).minusMillis(1L));

    assertRuleChange(originals.get(2), Type.ORIGINAL, new UUID(0, 3), new UUID(0, 2),
            new String[]{"ELECTRONIC", "CME", "ED", "US", "INDEX"}, Collections.singletonMap("Rate", "1.3"),
            NOW.plus(Period.ofWeeks(6)), NOW.plus(Period.ofWeeks(8)));

    final List<RuleChange> newChanges = getChangesByType(changes, Type.NEW);
    assertThat(newChanges, hasSize(1));

    assertRuleChange(newChanges.get(0), Type.NEW, null, new UUID(0, 2),
            new String[]{"VOICE", "CME", "ED", "US", "INDEX"}, Collections.singletonMap("Rate", "1.1"),
            NOW.plus(Period.ofWeeks(1)), NOW.plus(Period.ofWeeks(9)));
}
 
源代码23 项目: morpheus-core   文件: RangeBasicTests.java
@DataProvider(name="localDateRanges")
public Object[][] localDateRanges() {
    return new Object[][] {
            { LocalDate.of(1990, 1, 1), LocalDate.of(1990, 12, 31), Period.ofDays(1), false },
            { LocalDate.of(1990, 1, 1), LocalDate.of(1990, 12, 31), Period.ofDays(5), false },
            { LocalDate.of(2014, 12, 1), LocalDate.of(2013, 1, 1), Period.ofDays(3), false },
            { LocalDate.of(2014, 12, 1), LocalDate.of(2014, 1, 1), Period.ofDays(7), false },
            { LocalDate.of(1990, 1, 1), LocalDate.of(1990, 12, 31), Period.ofDays(1), true },
            { LocalDate.of(1990, 1, 1), LocalDate.of(1990, 12, 31), Period.ofDays(5), true },
            { LocalDate.of(2014, 12, 1), LocalDate.of(2013, 1, 1), Period.ofDays(3), true },
            { LocalDate.of(2014, 12, 1), LocalDate.of(2014, 1, 1), Period.ofDays(7), true },
    };
}
 
源代码24 项目: dbeam   文件: PsqlReplicationCheckTest.java
@Test
public void shouldBeReplicationDelayedWhenReplicatedBeforePartitionStart() {
  Instant partition = Instant.parse("2027-07-31T00:00:00Z");
  Instant lastReplication = Instant.parse("2027-07-30T22:00:00Z");
  Period partitionPeriod = Period.ofDays(1);

  Assert.assertTrue(
      PsqlReplicationCheck.isReplicationDelayed(partition, lastReplication, partitionPeriod));
}
 
源代码25 项目: openjdk-jdk9   文件: TCKPeriod.java
@Test
public void test_minusYears() {
    assertPeriod(Period.of(1, 2, 3).minusYears(0), 1, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minusYears(10), -9, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minusYears(-10), 11, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minusYears(-1), 2, 2, 3);

    assertPeriod(Period.of(1, 2, 3).minus(Period.ofYears(0)), 1, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minus(Period.ofYears(10)), -9, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minus(Period.ofYears(-10)), 11, 2, 3);
    assertPeriod(Period.of(1, 2, 3).minus(Period.ofYears(-1)), 2, 2, 3);
}
 
源代码26 项目: Strata   文件: XCcyIborIborSwapTemplateTest.java
@Test
public void test_of() {
  XCcyIborIborSwapTemplate test = XCcyIborIborSwapTemplate.of(Period.ofMonths(3), TENOR_10Y, CONV);
  assertThat(test.getPeriodToStart()).isEqualTo(Period.ofMonths(3));
  assertThat(test.getTenor()).isEqualTo(TENOR_10Y);
  assertThat(test.getConvention()).isEqualTo(CONV);
  assertThat(test.getCurrencyPair()).isEqualTo(EUR_USD);
}
 
源代码27 项目: journaldev   文件: DateAPIUtilities.java
public static void main(String[] args) {

		LocalDate today = LocalDate.now();

		// Get the Year, check if it's leap year
		System.out.println("Year " + today.getYear() + " is Leap Year? " + today.isLeapYear());

		// Compare two LocalDate for before and after
		System.out.println("Today is before 01/01/2015? " + today.isBefore(LocalDate.of(2015, 1, 1)));

		// Create LocalDateTime from LocalDate
		System.out.println("Current Time=" + today.atTime(LocalTime.now()));

		// plus and minus operations
		System.out.println("10 days after today will be " + today.plusDays(10));
		System.out.println("3 weeks after today will be " + today.plusWeeks(3));
		System.out.println("20 months after today will be " + today.plusMonths(20));

		System.out.println("10 days before today will be " + today.minusDays(10));
		System.out.println("3 weeks before today will be " + today.minusWeeks(3));
		System.out.println("20 months before today will be " + today.minusMonths(20));

		// Temporal adjusters for adjusting the dates
		System.out.println("First date of this month= " + today.with(TemporalAdjusters.firstDayOfMonth()));
		LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
		System.out.println("Last date of this year= " + lastDayOfYear);

		Period period = today.until(lastDayOfYear);
		System.out.println("Period Format= " + period);
		System.out.println("Months remaining in the year= " + period.getMonths());
	}
 
源代码28 项目: hibernate-types   文件: PostgreSQLPeriodType.java
@Override
protected void set(PreparedStatement st, Period value, int index, SharedSessionContractImplementor session) throws SQLException {
    if (value == null) {
        st.setNull(index, Types.OTHER);
    } else {
        final int days = value.getDays();
        final int months = value.getMonths();
        final int years = value.getYears();
        st.setObject(index, new PGInterval(years, months, days, 0, 0, 0));
    }
}
 
@Test
public void givenPeriodValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
    String serialized = serialization.serialize( Period.of( 3, 5, 13 ) );
    System.out.println( serialized );
    assertThat( getSingleStringRawState( serialized ), equalTo( "P3Y5M13D" ) );

    Period deserialized = serialization.deserialize( module, Period.class, serialized );
    assertThat( deserialized, equalTo( Period.of( 3, 5, 13 ) ) );
}
 
源代码30 项目: Strata   文件: FpmlDocument.java
/**
 * Converts an FpML 'AdjustedRelativeDateOffset' to a resolved {@code LocalDate}.
 * 
 * @param baseEl  the FpML adjustable date element
 * @return the resolved date
 * @throws RuntimeException if unable to parse
 */
public AdjustableDate parseAdjustedRelativeDateOffset(XmlElement baseEl) {
  // FpML content: ('periodMultiplier', 'period', 'dayType?',
  //                'businessDayConvention', 'BusinessCentersOrReference.model?'
  //                'dateRelativeTo', 'adjustedDate', 'relativeDateAdjustments?')
  // The 'adjustedDate' element is ignored
  XmlElement relativeToEl = lookupReference(baseEl.getChild("dateRelativeTo"));
  LocalDate baseDate;
  if (relativeToEl.hasContent()) {
    baseDate = parseDate(relativeToEl);
  } else if (relativeToEl.getName().contains("relative")) {
    baseDate = parseAdjustedRelativeDateOffset(relativeToEl).getUnadjusted();
  } else {
    throw new FpmlParseException(
        "Unable to resolve 'dateRelativeTo' to a date: " + baseEl.getChild("dateRelativeTo").getAttribute(HREF));
  }
  Period period = parsePeriod(baseEl);
  Optional<XmlElement> dayTypeEl = baseEl.findChild("dayType");
  boolean calendarDays = period.isZero() || (dayTypeEl.isPresent() && dayTypeEl.get().getContent().equals("Calendar"));
  BusinessDayAdjustment bda1 = parseBusinessDayAdjustments(baseEl);
  BusinessDayAdjustment bda2 = baseEl.findChild("relativeDateAdjustments")
      .map(el -> parseBusinessDayAdjustments(el))
      .orElse(bda1);
  // interpret and resolve, simple calendar arithmetic or business days
  LocalDate resolvedDate;
  if (period.getYears() > 0 || period.getMonths() > 0 || calendarDays) {
    resolvedDate = bda1.adjust(baseDate.plus(period), refData);
  } else {
    LocalDate datePlusBusDays = bda1.getCalendar().resolve(refData).shift(baseDate, period.getDays());
    resolvedDate = bda1.adjust(datePlusBusDays, refData);
  }
  return AdjustableDate.of(resolvedDate, bda2);
}
 
 类所在包
 同包方法