Java Code Examples for java.time.Period

The following examples show how to use java.time.Period. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Strata   Source File: RatesCalibrationCsvLoader.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 2
@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
        }
    }
}
 
Example 3
Source Project: Strata   Source File: InflationRateCalculationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
@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);
}
 
Example 5
@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);
        }
    }
}
 
Example 6
@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);
}
 
Example 7
@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
        }
    }
}
 
Example 8
Source Project: tutorials   Source File: CustomTemporalAdjusterUnitTest.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 9
Source Project: jdk8u-jdk   Source File: TCKYear.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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)},
    };
}
 
Example 10
Source Project: armeria   Source File: AnnotatedValueResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
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) {}
 
Example 11
Source Project: openjdk-8-source   Source File: TCKYear.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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)},
    };
}
 
Example 12
@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");
    }
}
 
Example 13
@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)));
}
 
Example 14
Source Project: jdk8u60   Source File: TCKPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example 15
@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);
    }
}
 
Example 16
Source Project: yago3   Source File: AgeExtractor.java    License: GNU General Public License v3.0 5 votes vote down vote up
/** 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();
}
 
Example 17
Source Project: jdk8u-jdk   Source File: TCKPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example 18
Source Project: openjdk-8-source   Source File: TCKPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 19
Source Project: jdk8u60   Source File: Parsed.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
    }
}
 
Example 20
Source Project: alibaba-rsocket-broker   Source File: PeriodSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
    if (obj == null) {
        out.writeNull();
    } else {
        out.writeObject(new PeriodHandle((Period) obj));
    }
}
 
Example 21
Source Project: hottub   Source File: TCKPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example 22
@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)));
}
 
Example 23
Source Project: morpheus-core   Source File: RangeBasicTests.java    License: Apache License 2.0 5 votes vote down vote up
@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 },
    };
}
 
Example 24
Source Project: dbeam   Source File: PsqlReplicationCheckTest.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 25
Source Project: openjdk-jdk9   Source File: TCKPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example 26
Source Project: Strata   Source File: XCcyIborIborSwapTemplateTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 27
Source Project: journaldev   Source File: DateAPIUtilities.java    License: MIT License 5 votes vote down vote up
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());
	}
 
Example 28
Source Project: hibernate-types   Source File: PostgreSQLPeriodType.java    License: Apache License 2.0 5 votes vote down vote up
@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));
    }
}
 
Example 29
@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 ) ) );
}
 
Example 30
Source Project: Strata   Source File: FpmlDocument.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}