下面列出了java.time.LocalDate#plusYears ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Create a new date by "adding" a year fraction to the start date.
* The year fraction is interpreted in a 30/360 way. More specifically,
* every integer unit advances by a year, each remaining fraction of 12
* advances by a month and each remaining fraction of 30 advances a day.
*
* The function may be used to ease the creation of maturities in spreadsheets.
*
* @param baseDate The start date.
* @param offsetYearFrac The year fraction in 30/360 to be used for adding to the start date.
* @return A date corresponding the maturity.
*/
private static LocalDate createDateFromDateAndOffset(final LocalDate baseDate, double offsetYearFrac) {
// Years
LocalDate maturity = baseDate.plusYears((int)offsetYearFrac);
// Months
offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 12;
maturity = maturity.plusMonths((int)offsetYearFrac);
// Days
offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 30;
maturity = maturity.plusDays((int)Math.round(offsetYearFrac));
return maturity;
}
/**
* Generate a schedule with start / end date determined by an offset from the reference date.
*
* @param referenceDate The reference date (corresponds to \( t = 0 \).
* @param maturity Offset of the start date to the reference date
* @param termination Offset of the end date to the start date
* @param unit The convention to use for the offset
* @return The schedule
*/
public Schedule generateSchedule(final LocalDate referenceDate, final int maturity, final int termination, final OffsetUnit unit) {
LocalDate startDate;
LocalDate endDate;
switch(unit) {
case YEARS : startDate = referenceDate.plusYears(maturity); endDate = startDate.plusYears(termination); break;
case MONTHS : startDate = referenceDate.plusMonths(maturity); endDate = startDate.plusMonths(termination); break;
case DAYS : startDate = referenceDate.plusDays(maturity); endDate = startDate.plusDays(termination); break;
case WEEKS : startDate = referenceDate.plusDays(maturity *7); endDate = startDate.plusDays(termination *7); break;
default : startDate = referenceDate.plusMonths(maturity); endDate = startDate.plusMonths(termination); break;
}
return generateSchedule(referenceDate, startDate, endDate);
}
/**
* Generate a schedule with start / end date determined by an offset from the reference date.
*
* @param referenceDate The reference date (corresponds to \( t = 0 \).
* @param maturity Offset of the start date to the reference date
* @param termination Offset of the end date to the start date
* @param unit The convention to use for the offset
* @return The schedule
*/
public Schedule generateSchedule(final LocalDate referenceDate, final int maturity, final int termination, final OffsetUnit unit) {
LocalDate startDate;
LocalDate endDate;
switch(unit) {
case YEARS : startDate = referenceDate.plusYears(maturity); endDate = startDate.plusYears(termination); break;
case MONTHS : startDate = referenceDate.plusMonths(maturity); endDate = startDate.plusMonths(termination); break;
case DAYS : startDate = referenceDate.plusDays(maturity); endDate = startDate.plusDays(termination); break;
case WEEKS : startDate = referenceDate.plusDays(maturity *7); endDate = startDate.plusDays(termination *7); break;
default : startDate = referenceDate.plusMonths(maturity); endDate = startDate.plusMonths(termination); break;
}
return generateSchedule(referenceDate, startDate, endDate);
}
@Test()
public void testFilter1() {
final LocalDate start = LocalDate.of(2000, 1, 1);
final LocalDate end = start.plusYears(10);
final Index<LocalDate> dates = Range.of(start, end).toIndex(LocalDate.class);
final Index<String> strings = Range.of(0, 100).map(i -> "Column-" +i).toIndex(String.class);
final DataFrame<String,LocalDate> frame = DataFrame.ofDoubles(strings, dates);
frame.applyDoubles(v -> Math.random() * 100);
final DataFrameColumns<String,LocalDate> filter = frame.cols().filter(Arrays.asList(dates.getKey(0), dates.getKey(25), dates.getKey(102), dates.getKey(456)));
Assert.assertEquals(filter.count(), 4, "Column count matches expected column count");
filter.forEach(column -> column.forEachValue(v -> {
final double actual = v.getDouble();
final double expected = frame.data().getDouble(v.rowKey(), v.colKey());
Assert.assertEquals(actual, expected, "The value matches for " + v);
}));
}
private LocalDate dateFromOffset(final LocalDate startDate, final int offset) {
LocalDate date = null;
switch(convention) {
case YEARS:
date = startDate.plusYears(offset);
break;
case MONTHS:
date = startDate.plusMonths(offset);
break;
case DAYS:
date = startDate.plusDays(offset);
break;
case WEEKS:
date = startDate.plusWeeks(offset);
break;
default:
throw new IllegalArgumentException("Unknown convention " + convention + ".");
}
return date;
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLarge() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1);
test.plusYears(1);
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLarge() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1);
test.plusYears(1);
}
@Test
@Deployment(resources = { "org/flowable/engine/test/api/oneTaskProcess.bpmn20.xml" })
public void testQueryLocalDateVariable() throws Exception {
Map<String, Object> vars = new HashMap<>();
LocalDate localDate = LocalDate.now();
vars.put("localDateVar", localDate);
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
LocalDate localDate2 = localDate.plusDays(1);
vars = new HashMap<>();
vars.put("localDateVar", localDate);
vars.put("localDateVar2", localDate2);
ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
LocalDate nextYear = localDate.plusYears(1);
vars = new HashMap<>();
vars.put("localDateVar", nextYear);
ProcessInstance processInstance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
LocalDate nextMonth = localDate.plusMonths(1);
LocalDate twoYearsLater = localDate.plusYears(2);
LocalDate oneYearAgo = localDate.minusYears(1);
// Query on single localDate variable, should result in 2 matches
ExecutionQuery query = runtimeService.createExecutionQuery().variableValueEquals("localDateVar", localDate);
List<Execution> executions = query.list();
assertThat(executions).hasSize(2);
// Query on two localDate variables, should result in single value
query = runtimeService.createExecutionQuery().variableValueEquals("localDateVar", localDate).variableValueEquals("localDateVar2", localDate2);
Execution execution = query.singleResult();
assertThat(execution).isNotNull();
assertThat(execution.getId()).isEqualTo(processInstance2.getId());
// Query with unexisting variable value
execution = runtimeService.createExecutionQuery().variableValueEquals("localDateVar", localDate.minusDays(1)).singleResult();
assertThat(execution).isNull();
// Test NOT_EQUALS
execution = runtimeService.createExecutionQuery().variableValueNotEquals("localDateVar", localDate).singleResult();
assertThat(execution).isNotNull();
assertThat(execution.getId()).isEqualTo(processInstance3.getId());
// Test GREATER_THAN
execution = runtimeService.createExecutionQuery().variableValueGreaterThan("localDateVar", nextMonth).singleResult();
assertThat(execution).isNotNull();
assertThat(execution.getId()).isEqualTo(processInstance3.getId());
assertThat(runtimeService.createExecutionQuery().variableValueGreaterThan("localDateVar", nextYear).count()).isZero();
assertThat(runtimeService.createExecutionQuery().variableValueGreaterThan("localDateVar", oneYearAgo).count()).isEqualTo(3);
// Test GREATER_THAN_OR_EQUAL
execution = runtimeService.createExecutionQuery().variableValueGreaterThanOrEqual("localDateVar", nextMonth).singleResult();
assertThat(execution).isNotNull();
assertThat(execution.getId()).isEqualTo(processInstance3.getId());
execution = runtimeService.createExecutionQuery().variableValueGreaterThanOrEqual("localDateVar", nextYear).singleResult();
assertThat(execution).isNotNull();
assertThat(execution.getId()).isEqualTo(processInstance3.getId());
assertThat(runtimeService.createExecutionQuery().variableValueGreaterThanOrEqual("localDateVar", oneYearAgo).count()).isEqualTo(3);
// Test LESS_THAN
executions = runtimeService.createExecutionQuery().variableValueLessThan("localDateVar", nextYear).list();
assertThat(executions)
.extracting(Execution::getId)
.containsExactlyInAnyOrder(
processInstance1.getId(),
processInstance2.getId()
);
assertThat(runtimeService.createExecutionQuery().variableValueLessThan("localDateVar", localDate).count()).isZero();
assertThat(runtimeService.createExecutionQuery().variableValueLessThan("localDateVar", twoYearsLater).count()).isEqualTo(3);
// Test LESS_THAN_OR_EQUAL
executions = runtimeService.createExecutionQuery().variableValueLessThanOrEqual("localDateVar", nextYear).list();
assertThat(executions).hasSize(3);
assertThat(runtimeService.createExecutionQuery().variableValueLessThanOrEqual("localDateVar", oneYearAgo).count()).isZero();
// Test value-only matching
execution = runtimeService.createExecutionQuery().variableValueEquals(nextYear).singleResult();
assertThat(execution).isNotNull();
assertThat(execution.getId()).isEqualTo(processInstance3.getId());
executions = runtimeService.createExecutionQuery().variableValueEquals(localDate).list();
assertThat(executions)
.extracting(Execution::getId)
.containsExactlyInAnyOrder(
processInstance1.getId(),
processInstance2.getId()
);
execution = runtimeService.createExecutionQuery().variableValueEquals(twoYearsLater).singleResult();
assertThat(execution).isNull();
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLarge() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1);
test.plusYears(1);
}
@BeforeClass
public static void create(){
final LocalDate referenceDate = LocalDate.of(2017, 8, 30);
final LocalDate startDate = referenceDate.plusYears(10);
final LocalDate endDate = startDate.plusYears(20);
final SchedulePrototype floatMetaSchedule = new SchedulePrototype(
Frequency.SEMIANNUAL,
DaycountConvention.ACT_360,
ShortPeriodConvention.LAST,
DateRollConvention.FOLLOWING,
new BusinessdayCalendarExcludingTARGETHolidays(),
0, 0, false);
final SchedulePrototype fixMetaSchedule = new SchedulePrototype(
Frequency.ANNUAL,
DaycountConvention.ACT_360,
ShortPeriodConvention.LAST,
DateRollConvention.FOLLOWING,
new BusinessdayCalendarExcludingTARGETHolidays(),
0, 0, false);
fixSchedule = fixMetaSchedule.generateSchedule(referenceDate, startDate, endDate);
floatSchedule = floatMetaSchedule.generateSchedule(referenceDate, startDate, endDate);
//Get curves
DiscountCurve discountCurve = null;
DiscountCurve forwardDiscountCurve = null;
ForwardCurve forwardCurve = null;
try (ObjectInputStream discountIn = new ObjectInputStream(new FileInputStream(new File(curveFilePath, discountCurveFileName)));
ObjectInputStream forwardIn = new ObjectInputStream(new FileInputStream(new File(curveFilePath, forwardCurveFileName)))) {
discountCurve = (DiscountCurve) discountIn.readObject();
forwardDiscountCurve = (DiscountCurve) forwardIn.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
forwardCurve = new ForwardCurveFromDiscountCurve("Forward-" + forwardDiscountCurve.getName(), forwardDiscountCurve.getName(), discountCurve.getName(), referenceDate, "6M",
new BusinessdayCalendarExcludingWeekends(), BusinessdayCalendar.DateRollConvention.FOLLOWING, 1, 0);
model = new AnalyticModelWithVolatilityCubes();
model = (AnalyticModelWithVolatilityCubes) model.addCurve(discountCurve.getName(), discountCurve);
model = (AnalyticModelWithVolatilityCubes) model.addCurve(forwardCurve.getName(), forwardCurve);
model = (AnalyticModelWithVolatilityCubes) model.addCurve(forwardDiscountCurve.getName(), forwardDiscountCurve);
ForwardCurve forwardFromDiscountCurve = null;
forwardFromDiscountCurve = new ForwardCurveFromDiscountCurve(discountCurve.getName(), referenceDate, "6M");
forwardAnnuity = SwapAnnuity.getSwapAnnuity(fixSchedule.getFixing(0), fixSchedule, discountCurve, null);
discountCurveSwapRate = Swap.getForwardSwapRate(fixSchedule, floatSchedule, forwardFromDiscountCurve, model);
forwardCurveSwapRate = Swap.getForwardSwapRate(fixSchedule, floatSchedule, forwardCurve, model);
//Cube
final String cubeName = "VOLA";
final VolatilityCube cube = createVolatilityCube(cubeName, referenceDate, forwardCurveSwapRate);
model = model.addVolatilityCube(cubeName, cube);
System.out.println("Projected forward annuity is \t" + forwardAnnuity +
"\t(Evaluated by adjusting the annuity given the current information with the discount at time of fixing.)" + "\n");
System.out.println("Swap rate from discount curve is \t" + discountCurveSwapRate);
System.out.println("Swap rate from forward curve is \t" +forwardCurveSwapRate +'\n');
basicPiterbarg = new BasicPiterbargAnnuityMapping(fixSchedule, floatSchedule, model, discountCurve.getName(), cubeName);
multiPiterbarg = new MultiPiterbargAnnuityMapping(fixSchedule, floatSchedule, model, discountCurve.getName(), forwardCurve.getName(), cubeName);
simpleMapping = new SimplifiedLinearAnnuityMapping(fixSchedule, floatSchedule, model, discountCurve.getName());
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLargeMaxAddMax() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1);
test.plusYears(Long.MAX_VALUE);
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLargeMaxAddMax() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1);
test.plusYears(Long.MAX_VALUE);
}
@BeforeClass
public static void create(){
final LocalDate referenceDate = LocalDate.of(2017, 8, 30);
final LocalDate startDate = referenceDate.plusYears(10);
final LocalDate endDate = startDate.plusYears(20);
final SchedulePrototype floatMetaSchedule = new SchedulePrototype(
Frequency.SEMIANNUAL,
DaycountConvention.ACT_360,
ShortPeriodConvention.LAST,
DateRollConvention.FOLLOWING,
new BusinessdayCalendarExcludingTARGETHolidays(),
0, 0, false);
final SchedulePrototype fixMetaSchedule = new SchedulePrototype(
Frequency.ANNUAL,
DaycountConvention.ACT_360,
ShortPeriodConvention.LAST,
DateRollConvention.FOLLOWING,
new BusinessdayCalendarExcludingTARGETHolidays(),
0, 0, false);
fixSchedule = fixMetaSchedule.generateSchedule(referenceDate, startDate, endDate);
floatSchedule = floatMetaSchedule.generateSchedule(referenceDate, startDate, endDate);
//Get curves
DiscountCurve discountCurve = null;
DiscountCurve forwardDiscountCurve = null;
ForwardCurve forwardCurve = null;
try (ObjectInputStream discountIn = new ObjectInputStream(new FileInputStream(new File(curveFilePath, discountCurveFileName)));
ObjectInputStream forwardIn = new ObjectInputStream(new FileInputStream(new File(curveFilePath, forwardCurveFileName)))) {
discountCurve = (DiscountCurve) discountIn.readObject();
forwardDiscountCurve = (DiscountCurve) forwardIn.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
forwardCurve = new ForwardCurveFromDiscountCurve("Forward-" + forwardDiscountCurve.getName(), forwardDiscountCurve.getName(), discountCurve.getName(), referenceDate, "6M",
new BusinessdayCalendarExcludingWeekends(), BusinessdayCalendar.DateRollConvention.FOLLOWING, 1, 0);
model = new AnalyticModelWithVolatilityCubes();
model = (AnalyticModelWithVolatilityCubes) model.addCurve(discountCurve.getName(), discountCurve);
model = (AnalyticModelWithVolatilityCubes) model.addCurve(forwardCurve.getName(), forwardCurve);
model = (AnalyticModelWithVolatilityCubes) model.addCurve(forwardDiscountCurve.getName(), forwardDiscountCurve);
ForwardCurve forwardFromDiscountCurve = null;
forwardFromDiscountCurve = new ForwardCurveFromDiscountCurve(discountCurve.getName(), referenceDate, "6M");
forwardAnnuity = SwapAnnuity.getSwapAnnuity(fixSchedule.getFixing(0), fixSchedule, discountCurve, null);
discountCurveSwapRate = Swap.getForwardSwapRate(fixSchedule, floatSchedule, forwardFromDiscountCurve, model);
forwardCurveSwapRate = Swap.getForwardSwapRate(fixSchedule, floatSchedule, forwardCurve, model);
//Cube
final String cubeName = "VOLA";
final VolatilityCube cube = createVolatilityCube(cubeName, referenceDate, forwardCurveSwapRate);
model = model.addVolatilityCube(cubeName, cube);
System.out.println("Projected forward annuity is \t" + forwardAnnuity +
"\t(Evaluated by adjusting the annuity given the current information with the discount at time of fixing.)" + "\n");
System.out.println("Swap rate from discount curve is \t" + discountCurveSwapRate);
System.out.println("Swap rate from forward curve is \t" +forwardCurveSwapRate +'\n');
basicPiterbarg = new BasicPiterbargAnnuityMapping(fixSchedule, floatSchedule, model, discountCurve.getName(), cubeName);
multiPiterbarg = new MultiPiterbargAnnuityMapping(fixSchedule, floatSchedule, model, discountCurve.getName(), forwardCurve.getName(), cubeName);
simpleMapping = new SimplifiedLinearAnnuityMapping(fixSchedule, floatSchedule, model, discountCurve.getName());
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLarge() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1);
test.plusYears(1);
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLarge() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1);
test.plusYears(1);
}
@Override
public double getDaycountFraction(final LocalDate startDate, final LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycountFraction(endDate,startDate);
}
/*
* Determine the denominator of act/act.
*/
double denominator;
final LocalDate startDatePlusOneYear = startDate.plusYears(1);
if(endDate.isAfter(startDatePlusOneYear)) {
/*
* The following method applies, if the interval spans more than one year:
* fraction = actual number of days / average number of days per year.
*/
final LocalDate startDateYearStart = startDate.withDayOfYear(1);
final LocalDate endDateYearEnd = endDate.withDayOfYear(endDate.lengthOfYear()).plusDays(1);
final double spannedYears = endDate.getYear() - startDate.getYear() + 1;
denominator = getDaycount(startDateYearStart, endDateYearEnd) / spannedYears;
}
else {
final boolean isStartLeapYear = startDate.isLeapYear();
final boolean isEndLeapYear = endDate.isLeapYear();
/*
* If the start and end span less or equal one year:
* If start and end fall in a leap year, use ACT/366.
*/
if(isStartLeapYear && isEndLeapYear)
{
denominator = 366.0;
}
else
/*
* If the start and end span less or equal one year:
* If either falls in a leap year and Feb 29th of that leap year lies in between start and end (or is equal to start or end), use ACT/366.
*/
if(isStartLeapYear || isEndLeapYear)
{
// Get February 29th of the respective leap year
final LocalDate leapYearsFeb29th = isStartLeapYear ?
LocalDate.of(startDate.getYear(), Month.FEBRUARY, 29) :
LocalDate.of(endDate.getYear(), Month.FEBRUARY, 29);
// Check position of February 29th
if(startDate.compareTo(leapYearsFeb29th) <= 0 && endDate.compareTo(leapYearsFeb29th) >= 0) {
denominator = 366.0;
}
else {
denominator = 365.0;
}
}
else {
/*
* If the start and end span less or equal one year:
* If none of the above applies, use denominator = ACT/365.
*/
denominator = 365.0;
}
}
final double daycountFraction = getDaycount(startDate, endDate) / denominator;
return daycountFraction;
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLargeMaxAddMin() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1);
test.plusYears(Long.MIN_VALUE);
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLargeMaxAddMin() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1);
test.plusYears(Long.MIN_VALUE);
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLarge() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1);
test.plusYears(1);
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plusYears_long_invalidTooLargeMaxAddMax() {
LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1);
test.plusYears(Long.MAX_VALUE);
}