下面列出了java.time.LocalDate#isAfter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public LocalDate getMostOldDatePaymentScheduleLine(
List<PaymentScheduleLine> paymentScheduleLineList) {
LocalDate minPaymentScheduleLineDate = LocalDate.now();
if (paymentScheduleLineList != null && !paymentScheduleLineList.isEmpty()) {
for (PaymentScheduleLine paymentScheduleLine : paymentScheduleLineList) {
if (minPaymentScheduleLineDate.isAfter(paymentScheduleLine.getScheduleDate())) {
minPaymentScheduleLineDate = paymentScheduleLine.getScheduleDate();
}
}
} else {
minPaymentScheduleLineDate = null;
}
return minPaymentScheduleLineDate;
}
private void init(Path directory, String baseFilename) {
List<Filename> filenames = FileMgr.scan(directory, baseFilename, patternFilenameDate);
if ( filenames.isEmpty() )
latestFilename = null;
else {
LocalDate dateLast = filenameToDate(Collections.max(filenames, cmpDate));
LocalDate dateFirst = filenameToDate(Collections.min(filenames, cmpDate));
int problems = 0;
if ( dateLast.isAfter(current)) {
problems++;
FmtLog.warn(LOG, "Latest output file is dated after today: %s > %s", dateLast, current);
}
if ( dateFirst.isAfter(current)) {
problems++;
FmtLog.warn(LOG, "First output file is dated after today: %s > %s", dateFirst, current);
}
if ( problems > 0 )
throw new FileRotateException("Existing files dated into the future");
latestFilename = filename(dateLast);
}
}
/**
* Resolves the sequence to a list of steps.
*
* @param existingSteps the existing list of steps
* @param rollConv the roll convention
* @return the steps
*/
List<ValueStep> resolve(List<ValueStep> existingSteps, RollConvention rollConv) {
ImmutableList.Builder<ValueStep> steps = ImmutableList.builder();
steps.addAll(existingSteps);
LocalDate prev = firstStepDate;
LocalDate date = firstStepDate;
while (!date.isAfter(lastStepDate)) {
steps.add(ValueStep.of(date, adjustment));
prev = date;
date = rollConv.next(date, frequency);
}
if (!prev.equals(lastStepDate)) {
throw new IllegalArgumentException(Messages.format(
"ValueStepSequence lastStepDate did not match frequency '{}' using roll convention '{}', {} != {}",
frequency, rollConv, lastStepDate, prev));
}
return steps.build();
}
private double valuationCompositionFactor() {
LocalDate currentFixing = nextFixing;
LocalDate currentPublication = computation.calculatePublicationFromFixing(currentFixing);
if (rates.getValuationDate().equals(currentPublication) &&
!(currentFixing.isAfter(lastFixingNonCutoff))) { // If currentFixing > lastFixingNonCutoff, everything fixed
OptionalDouble fixedRate = indexFixingDateSeries.get(currentFixing);
if (fixedRate.isPresent()) {
nextFixing = computation.getFixingCalendar().next(nextFixing);
LocalDate effectiveDate = computation.calculateEffectiveFromFixing(currentFixing);
LocalDate maturityDate = computation.calculateMaturityFromEffective(effectiveDate);
double accrualFactor = dayCount.yearFraction(effectiveDate, maturityDate);
if (currentFixing.isBefore(lastFixingNonCutoff)) {
return 1.0d + accrualFactor * fixedRate.getAsDouble();
}
double compositionFactor = 1.0d + accrualFactor * fixedRate.getAsDouble();
for (int i = 0; i < cutoffOffset - 1; i++) {
compositionFactor *= 1.0d + accrualFactorCutoff[i] * fixedRate.getAsDouble();
}
return compositionFactor;
}
}
return 1.0d;
}
private static List<LocalDate> generateBackwards(
PeriodicSchedule schedule,
LocalDate start,
LocalDate end,
Frequency frequency,
RollConvention rollConv,
StubConvention stubConv,
LocalDate explicitStartDate) {
// validate
if (rollConv.matches(end) == false) {
throw new ScheduleException(
schedule, "Date '{}' does not match roll convention '{}' when starting to roll backwards", end, rollConv);
}
// generate
BackwardsList dates = new BackwardsList(estimateNumberPeriods(start, end, frequency));
dates.addFirst(end);
LocalDate temp = rollConv.previous(end, frequency);
while (temp.isAfter(start)) {
dates.addFirst(temp);
temp = rollConv.previous(temp, frequency);
}
// convert to long stub, but only if we actually have a stub
boolean stub = temp.equals(start) == false;
if (stub && dates.size() > 1 && stubConv.isStubLong(start, dates.get(0))) {
dates.removeFirst();
}
dates.addFirst(explicitStartDate);
return dates;
}
@Override
public HighlightInformation getHighlightInformationOrNull(LocalDate someDate) {
if (selectedDate == null) {
return null;
}
if ((someDate.isAfter(LocalDate.now()) || someDate.isEqual(LocalDate.now()))
&& (someDate.isBefore(selectedDate) || someDate.isEqual(selectedDate))) {
return new HighlightInformation(Color.GREEN, Color.BLACK, "selected period");
}
return null;
}
@Override
public double getDaycountFraction(final LocalDate startDate, final LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycountFraction(endDate,startDate);
}
final double daycountFraction = getDaycount(startDate, endDate) / 365.0;
return daycountFraction;
}
@Test
public void shouldDrawOneAsMinimum() {
LocalDate date = LocalDate.parse("2012-01-01");
LocalDate maxDate = LocalDate.parse("2013-01-01");
while (true) {
Draw draw = DrawingService.drawNumbers(date);
if (draw.getNumbers().contains(1)) {
break;
}
date = date.plusDays(1);
if (date.isAfter(maxDate)) {
fail("didn't find 1 in the draw");
}
}
}
@Override
public double getDaycount(final LocalDate startDate, final LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycount(endDate,startDate);
}
return daysBetween(startDate, endDate);
}
@Override
public double getDaycount(final LocalDate startDate, final LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycount(endDate,startDate);
}
// Get actual number of days
double daycount = DayCountConvention_ACT.daysBetween(startDate, endDate);
/*
* Remove leap days, if any.
*/
for(int year = startDate.getYear() ; year <= endDate.getYear(); year++) {
if (IsoChronology.INSTANCE.isLeapYear(year)) {
final LocalDate leapDay = LocalDate.of(year,Month.FEBRUARY, 29);
if(startDate.isBefore(leapDay) && !endDate.isBefore(leapDay)) {
daycount -= 1.0;
}
}
}
if(daycount < 0.0) {
throw new AssertionError("Daycount is negative for startDate not after endDate.");
}
return daycount;
}
@Override
public double getDaycountFraction(final LocalDate startDate, final LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycountFraction(endDate,startDate);
}
/*
* Number of whole years between start and end, excluding start's year and excluding end's year.
*
* If start and end fall in the same year, this is -1 (there will be a double counting of 1 year below if start < end).
* If start and end fall in separate but consecutive years, this is 0 (for start and end the fractional parts are counted individually below).
*/
double daycountFraction = endDate.getYear() - startDate.getYear() - 1.0;
/*
* Fraction from start to the end of start's year
*/
LocalDate startDateNextYear = LocalDate.of(startDate.getYear()+1,Month.JANUARY,1);
if(isCountLastDayNotFirst) {
startDateNextYear = startDateNextYear.minusDays(1);
}
daycountFraction += getDaycount(startDate, startDateNextYear) / startDate.lengthOfYear();
/*
* Fraction from beginning of end's year to end
*/
LocalDate endDateStartYear = LocalDate.of(endDate.getYear(), Month.JANUARY, 1);
if (isCountLastDayNotFirst) {
endDateStartYear = endDateStartYear.minusDays(1);
}
daycountFraction += getDaycount(endDateStartYear, endDate) / endDate.lengthOfYear();
return Math.max(daycountFraction,0.0);
}
private static void checkNotBefore(LocalDate notBeforeDate,
LocalDate distrustDate, X509Certificate anchor)
throws ValidatorException {
if (notBeforeDate.isAfter(distrustDate)) {
throw new ValidatorException
("TLS Server certificate issued after " + distrustDate +
" and anchored by a distrusted legacy Symantec root CA: "
+ anchor.getSubjectX500Principal(),
ValidatorException.T_UNTRUSTED_CERT, anchor);
}
}
/**
* Calculates the present value of the fixed coupon bond trade from the clean price of the underlying product.
* <p>
* The present value of the trade is the value on the valuation date.
* The result is expressed using the payment currency of the bond.
* <p>
* Coupon payments of the underlying product are considered based on the settlement date of the trade.
*
* @param trade the trade
* @param provider the discounting provider
* @param refData the reference data used to calculate the settlement date
* @param cleanPrice the clean price
* @return the present value of the fixed coupon bond trade
*/
public CurrencyAmount presentValueFromCleanPrice(
ResolvedFixedCouponBondTrade trade,
LegalEntityDiscountingProvider provider,
ReferenceData refData,
double cleanPrice) {
ResolvedFixedCouponBond product = trade.getProduct();
LocalDate standardSettlementDate = standardSettlementDate(product, provider, refData);
LocalDate tradeSettlementDate = settlementDate(trade, provider.getValuationDate());
Currency currency = product.getCurrency();
RepoCurveDiscountFactors repoDf = DiscountingFixedCouponBondProductPricer.repoCurveDf(product, provider);
double df = repoDf.discountFactor(standardSettlementDate);
double pvStandard =
(cleanPrice * product.getNotional() + productPricer.accruedInterest(product, standardSettlementDate)) * df;
if (standardSettlementDate.isEqual(tradeSettlementDate)) {
return presentValueFromProductPresentValue(trade, provider, CurrencyAmount.of(currency, pvStandard));
}
// check coupon payment between two settlement dates
IssuerCurveDiscountFactors issuerDf = DiscountingFixedCouponBondProductPricer.issuerCurveDf(product, provider);
double pvDiff = 0d;
if (standardSettlementDate.isAfter(tradeSettlementDate)) {
pvDiff = productPricer.presentValueCoupon(product, issuerDf, tradeSettlementDate, standardSettlementDate);
} else {
pvDiff = -productPricer.presentValueCoupon(product, issuerDf, standardSettlementDate, tradeSettlementDate);
}
return presentValueFromProductPresentValue(trade, provider, CurrencyAmount.of(currency, pvStandard + pvDiff));
}
@Override
public double getDaycountFraction(final LocalDate startDate, final LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycountFraction(endDate,startDate);
}
int periodIndexEndDate = Collections.binarySearch(periods, new Period(endDate, endDate, endDate, endDate));
int periodIndexStartDate = Collections.binarySearch(periods, new Period(startDate, startDate, startDate, startDate));
if(periodIndexEndDate < 0) {
periodIndexEndDate = -periodIndexEndDate-1;
}
if(periodIndexStartDate < 0) {
periodIndexStartDate = -periodIndexStartDate-1;
} else {
periodIndexStartDate = periodIndexStartDate+1;
}
final Period startDatePeriod = periods.get(periodIndexStartDate);
final Period endDatePeriod = periods.get(periodIndexEndDate);
final double periodFraction =
getDaycount(startDate, startDatePeriod.getPeriodEnd()) / getDaycount(startDatePeriod.getPeriodStart(), startDatePeriod.getPeriodEnd())
+
getDaycount(endDatePeriod.getPeriodStart(), endDate) / getDaycount(endDatePeriod.getPeriodStart(), endDatePeriod.getPeriodEnd())
+
(periodIndexEndDate - periodIndexStartDate) - 1;
return periodFraction / frequency;
}
public boolean contains(LocalDate eventDate) {
if (eventDate.isAfter(to))
return false;
if (eventDate.isBefore(from))
return false;
return true;
}
/**
* @param range Date range to test for
* @param rc RevCommit to check
* @return True if the commit was made within the date range, false otherwise.
*/
private boolean isInDateRange(DateRange range, RevCommit rc) {
LocalDate commitTime =
Instant.ofEpochSecond(rc.getCommitTime()).atZone(ZoneId.systemDefault()).toLocalDate();
return (commitTime.isBefore(range.getEndDate()) || commitTime.isEqual(range.getEndDate()))
&& (commitTime.isAfter(range.getStartDate()) || commitTime.isEqual(range.getStartDate()));
}
@Override
public String getPfpValidatorUserDomain(Invoice invoice) {
User pfpValidatorUser = getPfpValidatorUser(invoice);
if (pfpValidatorUser == null) {
return "self.id in (0)";
}
List<SubstitutePfpValidator> substitutePfpValidatorList =
pfpValidatorUser.getSubstitutePfpValidatorList();
List<User> validPfpValidatorUserList = new ArrayList<>();
StringBuilder pfpValidatorUserDomain = new StringBuilder("self.id in ");
LocalDate todayDate = Beans.get(AppBaseService.class).getTodayDate();
validPfpValidatorUserList.add(pfpValidatorUser);
for (SubstitutePfpValidator substitutePfpValidator : substitutePfpValidatorList) {
LocalDate substituteStartDate = substitutePfpValidator.getSubstituteStartDate();
LocalDate substituteEndDate = substitutePfpValidator.getSubstituteEndDate();
if (substituteStartDate == null) {
if (substituteEndDate == null || substituteEndDate.isAfter(todayDate)) {
validPfpValidatorUserList.add(substitutePfpValidator.getSubstitutePfpValidatorUser());
}
} else {
if (substituteEndDate == null && substituteStartDate.isBefore(todayDate)) {
validPfpValidatorUserList.add(substitutePfpValidator.getSubstitutePfpValidatorUser());
} else if (substituteStartDate.isBefore(todayDate)
&& substituteEndDate.isAfter(todayDate)) {
validPfpValidatorUserList.add(substitutePfpValidator.getSubstitutePfpValidatorUser());
}
}
}
pfpValidatorUserDomain
.append("(")
.append(
validPfpValidatorUserList
.stream()
.map(pfpValidator -> pfpValidator.getId().toString())
.collect(Collectors.joining(",")))
.append(")");
return pfpValidatorUserDomain.toString();
}
/**
* Computes the present value curve sensitivity by simple forward rate estimation.
*
* @param cmsPeriod the CMS
* @param provider the rates provider
* @return the present value sensitivity
*/
public PointSensitivityBuilder presentValueSensitivity(
CmsPeriod cmsPeriod,
RatesProvider provider) {
Currency ccy = cmsPeriod.getCurrency();
LocalDate valuationDate = provider.getValuationDate();
if (valuationDate.isAfter(cmsPeriod.getPaymentDate())) {
return PointSensitivityBuilder.none();
}
LocalDate fixingDate = cmsPeriod.getFixingDate();
double dfPayment = provider.discountFactor(ccy, cmsPeriod.getPaymentDate());
if (!fixingDate.isAfter(valuationDate)) { // Using fixing
OptionalDouble fixedRate = provider.timeSeries(cmsPeriod.getIndex()).get(fixingDate);
if (fixedRate.isPresent()) {
double payoff = 0d;
switch (cmsPeriod.getCmsPeriodType()) {
case CAPLET:
payoff = Math.max(fixedRate.getAsDouble() - cmsPeriod.getStrike(), 0d);
break;
case FLOORLET:
payoff = Math.max(cmsPeriod.getStrike() - fixedRate.getAsDouble(), 0d);
break;
case COUPON:
payoff = fixedRate.getAsDouble();
break;
default:
throw new IllegalArgumentException("unsupported CMS type");
}
return provider.discountFactors(ccy).zeroRatePointSensitivity(
cmsPeriod.getPaymentDate()).multipliedBy(payoff * cmsPeriod.getNotional() * cmsPeriod.getYearFraction());
} else if (fixingDate.isBefore(valuationDate)) {
throw new IllegalArgumentException(Messages.format(
"Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.getIndex(), fixingDate));
}
}
if (!cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON)) {
throw new IllegalArgumentException("Unable to price cap or floor in this pricer");
}
// Using forward
ResolvedSwap swap = cmsPeriod.getUnderlyingSwap();
ZeroRateSensitivity dfPaymentdr = provider.discountFactors(ccy).zeroRatePointSensitivity(cmsPeriod.getPaymentDate());
double forward = swapPricer.parRate(swap, provider);
PointSensitivityBuilder forwardSensi = swapPricer.parRateSensitivity(swap, provider);
return forwardSensi.multipliedBy(dfPayment).combinedWith(dfPaymentdr.multipliedBy(forward))
.multipliedBy(cmsPeriod.getNotional() * cmsPeriod.getYearFraction());
}
@Override
public ResponseEntity<ShimDataResponse> getData(
OAuth2RestOperations restTemplate,
ShimDataRequest shimDataRequest)
throws ShimException {
FitbitDataType fitbitDataType;
try {
fitbitDataType = FitbitDataType.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
}
catch (NullPointerException | IllegalArgumentException e) {
throw new ShimException("Null or Invalid data type parameter: "
+ shimDataRequest.getDataTypeKey()
+ " in shimDataRequest, cannot retrieve data.", e);
}
LocalDate today = LocalDate.now();
LocalDate startDate = shimDataRequest.getStartDateTime() == null
? today
: shimDataRequest.getStartDateTime().toLocalDate();
LocalDate endDate = shimDataRequest.getEndDateTime() == null
? today
: shimDataRequest.getEndDateTime().toLocalDate();
if (usesDateRangeQuery(fitbitDataType)) {
return getDataForDateRange(
restTemplate,
startDate,
endDate,
fitbitDataType,
shimDataRequest.getNormalize());
}
else {
/*
Fitbit's API forces you to make a request for each given day of data for some endpoints. Thus we
make a request for each day in the submitted time range and then aggregate the response based on the
normalization parameter.
*/
List<ShimDataResponse> dayResponses = new ArrayList<>();
LocalDate indexDate = startDate;
while (!indexDate.isAfter(endDate)) {
dayResponses.add(getDataForSingleDate(restTemplate, indexDate, fitbitDataType,
shimDataRequest.getNormalize()).getBody());
indexDate = indexDate.plusDays(1);
}
return shimDataRequest.getNormalize()
? ok(aggregateNormalized(dayResponses))
: ok(aggregateIntoList(dayResponses));
}
}
/**
* Computes the duration in days of a leave, according to the input planning.
*
* @param leave
* @param employee
* @param fromDate
* @param toDate
* @param startOn
* @param endOn
* @return
* @throws AxelorException
*/
protected BigDecimal computeDurationInDays(
LeaveRequest leave,
Employee employee,
LocalDate fromDate,
LocalDate toDate,
int startOn,
int endOn)
throws AxelorException {
BigDecimal duration = BigDecimal.ZERO;
WeeklyPlanning weeklyPlanning = getWeeklyPlanning(leave, employee);
EventsPlanning holidayPlanning = getPublicHolidayEventsPlanning(leave, employee);
// If the leave request is only for 1 day
if (fromDate.isEqual(toDate)) {
if (startOn == endOn) {
if (startOn == LeaveRequestRepository.SELECT_MORNING) {
duration =
duration.add(
BigDecimal.valueOf(
weeklyPlanningService.getWorkingDayValueInDaysWithSelect(
weeklyPlanning, fromDate, true, false)));
} else {
duration =
duration.add(
BigDecimal.valueOf(
weeklyPlanningService.getWorkingDayValueInDaysWithSelect(
weeklyPlanning, fromDate, false, true)));
}
} else {
duration =
duration.add(
BigDecimal.valueOf(
weeklyPlanningService.getWorkingDayValueInDaysWithSelect(
weeklyPlanning, fromDate, true, true)));
}
// Else if it's on several days
} else {
duration =
duration.add(
BigDecimal.valueOf(computeStartDateWithSelect(fromDate, startOn, weeklyPlanning)));
LocalDate itDate = fromDate.plusDays(1);
while (!itDate.isEqual(toDate) && !itDate.isAfter(toDate)) {
duration =
duration.add(
BigDecimal.valueOf(
weeklyPlanningService.getWorkingDayValueInDays(weeklyPlanning, itDate)));
itDate = itDate.plusDays(1);
}
duration =
duration.add(BigDecimal.valueOf(computeEndDateWithSelect(toDate, endOn, weeklyPlanning)));
}
if (holidayPlanning != null) {
duration =
duration.subtract(
publicHolidayHrService.computePublicHolidayDays(
fromDate, toDate, weeklyPlanning, holidayPlanning));
}
return duration;
}