下面列出了java.time.LocalDate#isBefore ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
GregorianCalendar cal = new GregorianCalendar();
assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);
cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
cal.set(Calendar.YEAR, isoDate.get(YEAR));
cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));
while (isoDate.isBefore(isoEndDate)) {
assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + "; cal: " + cal);
assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);
isoDate = isoDate.plus(1, ChronoUnit.DAYS);
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
GregorianCalendar cal = new GregorianCalendar();
assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);
cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
cal.set(Calendar.YEAR, isoDate.get(YEAR));
cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));
while (isoDate.isBefore(isoEndDate)) {
assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + "; cal: " + cal);
assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);
isoDate = isoDate.plus(1, ChronoUnit.DAYS);
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
@Override
public Boolean queryFrom(TemporalAccessor temporal) {
LocalDate date = LocalDate.from(temporal);
LocalDate secondSundayInMarch = LocalDate.from(date)
.withMonth(Month.MARCH.getValue())
.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY))
.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
LocalDate firstSundayInNovember = LocalDate.from(date)
.withMonth(Month.NOVEMBER.getValue())
.with(TemporalAdjusters.firstDayOfMonth())
.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
if (date.isAfter(secondSundayInMarch)
|| date.isBefore(firstSundayInNovember)) {
return true;
} else {
return false;
}
}
/**
* Gets the date range.
*
* @param from the from
* @param to the to
* @param excludeBefore the exclude before
* @param inputFormatter the input formatter
* @return the date range
*/
private List<String> getDateRange(Object from, Object to, LocalDate excludeBefore, DateTimeFormatter inputFormatter){
LocalDate fromDt;
LocalDate toDt;
List<String> dateRage = new ArrayList<>();
if(from!=null){
fromDt = LocalDateTime.parse(from.toString(),inputFormatter).toLocalDate();
if(to==null){
toDt = LocalDate.now();
}else{
toDt = LocalDateTime.parse(to.toString(),inputFormatter).toLocalDate();
}
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
while(fromDt.isBefore(toDt)){
if(!fromDt.isBefore(excludeBefore)){
dateRage.add(formatter.format(fromDt));
}
fromDt = fromDt.plusDays(1);
}
}
return dateRage;
}
@Override
public LocalDateDoubleTimeSeries subSeries(LocalDate startInclusive, LocalDate endExclusive) {
ArgChecker.notNull(startInclusive, "startInclusive");
ArgChecker.notNull(endExclusive, "endExclusive");
if (endExclusive.isBefore(startInclusive)) {
throw new IllegalArgumentException(
"Invalid sub series, end before start: " + startInclusive + " to " + endExclusive);
}
// special case when this is empty or when the dates are the same
if (isEmpty() || startInclusive.equals(endExclusive)) {
return EMPTY;
}
// where in the array would start/end be (whether or not it's actually in the series)
int startPos = Arrays.binarySearch(dates, startInclusive);
startPos = startPos >= 0 ? startPos : -startPos - 1;
int endPos = Arrays.binarySearch(dates, endExclusive);
endPos = endPos >= 0 ? endPos : -endPos - 1;
// create sub-series
LocalDate[] timesArray = Arrays.copyOfRange(dates, startPos, endPos);
double[] valuesArray = Arrays.copyOfRange(values, startPos, endPos);
return createUnsafe(timesArray, valuesArray);
}
/**
* 加载日线数据
*/
private LeveledBarSeries loadDaySeries() throws IOException
{
BaseLeveledBarSeries result = new BaseLeveledBarSeries(instrument, instrument.name()+"-"+resolvedLevel, resolvedLevel, LongNum::valueOf);
if ( !data.exists(instrument, ExchangeableData.DAY, null)) {
return result;
}
String csv = data.load(instrument, ExchangeableData.DAY, null);
CSVDataSet csvDataSet = CSVUtil.parse(csv);
int colIndex = csvDataSet.getColumnIndex(ExchangeableData.COLUMN_INDEX);
while(csvDataSet.next()) {
LocalDate date = csvDataSet.getDate(ExchangeableData.COLUMN_DATE);
if ( startTradingDay!=null && date.isBefore(startTradingDay)) {
continue;
}
//不包含当天
if ( endTradingDay!=null && date.compareTo(endTradingDay)>=0 ) {
continue;
}
FutureBar bar = FutureBar.fromDayCSV(csvDataSet, instrument);
result.addBar(bar);
}
return result;
}
@Override
public DateCell call(final DatePicker datePicker)
{
return new DateCell()
{
@Override
public void updateItem(LocalDate item, boolean empty)
{
super.updateItem(item, empty);
String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
LocalDate item2 = LocalDate.parse(date);
String[] days2 = days.split(" ");
for (int i = 0; i < days2.length; i++)
{
if (item.getDayOfWeek().getValue() == Integer.parseInt(days2[i]))
{
setDisable(true);
setStyle("-fx-background-color: #ffc0cb;");
}
}
if (item.isBefore(item2))
{
setDisable(true);
setStyle("-fx-background-color: #aaaaaa;");
}
if (item.isAfter(item2.plusDays(13)))
{
setDisable(true);
setStyle("-fx-background-color: #aaaaaa;");
}
setTooltip(new Tooltip("Make the appointment within 14 days"));
}
};
}
@Override
public double rate(
OvernightAveragedRateComputation computation,
LocalDate startDate,
LocalDate endDate,
RatesProvider provider) {
OvernightIndex index = computation.getIndex();
OvernightIndexRates rates = provider.overnightIndexRates(index);
LocalDate lastNonCutoffFixing = computation.getEndDate();
int cutoffOffset = computation.getRateCutOffDays() > 1 ? computation.getRateCutOffDays() : 1;
double accumulatedInterest = 0.0d;
double accrualFactorTotal = 0.0d;
// Cut-off period. Starting from the end as the cutoff period is defined as a lag from the end.
// When the fixing period end-date is not a good business day in the index calendar,
// the last fixing end date will be after the fixing end-date.
double cutoffAccrualFactor = 0.0;
OvernightIndexObservation lastIndexObs = null;
// cutoffOffset >= 1, so loop always runs at least once
for (int i = 0; i < cutoffOffset; i++) {
lastNonCutoffFixing = computation.getFixingCalendar().previous(lastNonCutoffFixing);
lastIndexObs = computation.observeOn(lastNonCutoffFixing);
accrualFactorTotal += lastIndexObs.getYearFraction();
cutoffAccrualFactor += lastIndexObs.getYearFraction();
}
double forwardRateCutOff = rates.rate(lastIndexObs);
accumulatedInterest += cutoffAccrualFactor * forwardRateCutOff;
LocalDate currentFixingNonCutoff = computation.getStartDate();
while (currentFixingNonCutoff.isBefore(lastNonCutoffFixing)) {
// All dates involved in the period are computed. Potentially slow.
// The fixing periods are added as long as their start date is (strictly) before the no cutoff period end-date.
OvernightIndexObservation indexObs = computation.observeOn(currentFixingNonCutoff);
double forwardRate = rates.rate(indexObs);
accrualFactorTotal += indexObs.getYearFraction();
accumulatedInterest += indexObs.getYearFraction() * forwardRate;
currentFixingNonCutoff = computation.getFixingCalendar().next(currentFixingNonCutoff);
}
// final rate
return accumulatedInterest / accrualFactorTotal;
}
@Override
public LocalDate nextOrSame(LocalDate date) {
if (date.isBefore(date(2015, 10, 16))) {
return date(2015, 10, 15);
}
if (date.isBefore(date(2015, 10, 23))) {
return date(2015, 10, 22);
}
if (date.isBefore(date(2015, 10, 30))) {
return date(2015, 10, 29);
}
throw new IllegalArgumentException();
}
/**
* Calculates the accrued premium per fractional spread for unit notional.
*
* @param stepinDate the step-in date
* @return the accrued year fraction
*/
public double accruedYearFraction(LocalDate stepinDate) {
if (stepinDate.isBefore(getAccrualStartDate())) {
return 0d;
}
if (stepinDate.isEqual(getAccrualEndDate())) {
return paymentPeriods.get(paymentPeriods.size() - 1).getYearFraction();
}
CreditCouponPaymentPeriod period = findPeriod(stepinDate)
.orElseThrow(() -> new IllegalArgumentException("Date outside range"));
return dayCount.relativeYearFraction(period.getStartDate(), stepinDate);
}
/**
* Constructs a {@code JapaneseDate}. This constructor does NOT validate the given parameters,
* and {@code era} and {@code year} must agree with {@code isoDate}.
*
* @param era the era, validated not null
* @param year the year-of-era, validated
* @param isoDate the standard local date, validated not null
*/
JapaneseDate(JapaneseEra era, int year, LocalDate isoDate) {
if (isoDate.isBefore(MEIJI_6_ISODATE)) {
throw new DateTimeException("JapaneseDate before Meiji 6 is not supported");
}
this.era = era;
this.yearOfEra = year;
this.isoDate = isoDate;
}
/**
* Constructs a {@code JapaneseDate}. This constructor does NOT validate the given parameters,
* and {@code era} and {@code year} must agree with {@code isoDate}.
*
* @param era the era, validated not null
* @param year the year-of-era, validated
* @param isoDate the standard local date, validated not null
*/
JapaneseDate(JapaneseEra era, int year, LocalDate isoDate) {
if (isoDate.isBefore(MEIJI_6_ISODATE)) {
throw new DateTimeException("JapaneseDate before Meiji 6 is not supported");
}
this.era = era;
this.yearOfEra = year;
this.isoDate = isoDate;
}
/**
* Creates an instance from an ISO date.
*
* @param isoDate the standard local date, validated not null
*/
JapaneseDate(LocalDate isoDate) {
if (isoDate.isBefore(MEIJI_6_ISODATE)) {
throw new DateTimeException("JapaneseDate before Meiji 6 is not supported");
}
LocalGregorianCalendar.Date jdate = toPrivateJapaneseDate(isoDate);
this.era = JapaneseEra.toJapaneseEra(jdate.getEra());
this.yearOfEra = jdate.getYear();
this.isoDate = isoDate;
}
@Override
public double getDaycountFraction(final LocalDate startDate, final LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycountFraction(endDate,startDate);
}
double daysPerYear = 365.0;
// Check startDate for leap year
if (startDate.isLeapYear()) {
final LocalDate leapDayStart = LocalDate.of(startDate.getYear(), Month.FEBRUARY, 29);
if(startDate.isBefore(leapDayStart) && !endDate.isBefore(leapDayStart)) {
daysPerYear = 366.0;
}
}
// Check endDate for leap year
if (endDate.isLeapYear()){
final LocalDate leapDayEnd = LocalDate.of(endDate.getYear(), Month.FEBRUARY, 29);
if(startDate.isBefore(leapDayEnd) && !endDate.isBefore(leapDayEnd)) {
daysPerYear = 366.0;
}
}
// Check in-between years for leap year
for(int year = startDate.getYear()+1; year < endDate.getYear(); year++) {
if(IsoChronology.INSTANCE.isLeapYear(year)) {
daysPerYear = 366.0;
}
}
final double daycountFraction = getDaycount(startDate, endDate) / daysPerYear;
return daycountFraction;
}
@Override
public Optional<Money> getAccommodationPrice(LocalDate date) {
var limit = LocalDate.now(clock).plusDays(MAX_DAYS_IN_FUTURE);
if (date.isBefore(limit)) {
return Optional.of(Money.of(ThreadLocalRandom.current().nextInt(50, 150), Hotel.CURRENCY));
} else {
return Optional.empty();
}
}
public static boolean isDateEarly(LocalDate ld1,LocalDate ld2){
return ld1.isBefore(ld2);
}
boolean isSurveyOpen() {
final LocalDate now = LocalDate.now();
return (now.isEqual(startDate) || now.isAfter(startDate)) && now.isBefore(endDate);
}
@Test(dataProvider = "RangeVersusCalendar")
public void test_DayOfWeek_IsoChronology_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
GregorianCalendar cal = new GregorianCalendar();
assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);
for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) {
for (int minDays = 1; minDays <= 7; minDays++) {
WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
cal.setFirstDayOfWeek(Math.floorMod(firstDayOfWeek.getValue(), 7) + 1);
cal.setMinimalDaysInFirstWeek(minDays);
cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
cal.set(Calendar.YEAR, isoDate.get(YEAR));
cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));
// For every date in the range
while (isoDate.isBefore(isoEndDate)) {
assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + "; cal: " + cal);
assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);
int jdow = Math.floorMod(cal.get(Calendar.DAY_OF_WEEK) - 2, 7) + 1;
int dow = isoDate.get(weekDef.dayOfWeek());
assertEquals(jdow, dow, "Calendar DayOfWeek does not match ISO DayOfWeek");
int jweekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
int isoWeekOfMonth = isoDate.get(weekDef.weekOfMonth());
assertEquals(jweekOfMonth, isoWeekOfMonth, "Calendar WeekOfMonth does not match ISO WeekOfMonth");
int jweekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
int weekOfYear = isoDate.get(weekDef.weekOfWeekBasedYear());
assertEquals(jweekOfYear, weekOfYear, "GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear");
int jWeekYear = cal.getWeekYear();
int weekBasedYear = isoDate.get(weekDef.weekBasedYear());
assertEquals(jWeekYear, weekBasedYear, "GregorianCalendar getWeekYear does not match YearOfWeekBasedYear");
int jweeksInWeekyear = cal.getWeeksInWeekYear();
int weeksInWeekBasedYear = (int)isoDate.range(weekDef.weekOfWeekBasedYear()).getMaximum();
assertEquals(jweeksInWeekyear, weeksInWeekBasedYear, "length of weekBasedYear");
isoDate = isoDate.plus(1, ChronoUnit.DAYS);
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
}
/**
* Gets the relative year fraction between the specified dates.
* <p>
* Given two dates, this method returns the fraction of a year between these
* dates according to the convention.
* The result of this method will be negative if the first date is after the second date.
* The result is calculated using {@link #yearFraction(LocalDate, LocalDate, ScheduleInfo)}.
*
* @param firstDate the first date
* @param secondDate the second date, which may be before the first date
* @param scheduleInfo the schedule information
* @return the year fraction, may be negative
* @throws UnsupportedOperationException if the year fraction cannot be obtained
*/
public default double relativeYearFraction(LocalDate firstDate, LocalDate secondDate, ScheduleInfo scheduleInfo) {
if (secondDate.isBefore(firstDate)) {
return -yearFraction(secondDate, firstDate, scheduleInfo);
}
return yearFraction(firstDate, secondDate, scheduleInfo);
}
/**
* Checks if this period contains the specified date, based on unadjusted dates.
* <p>
* The unadjusted start and end dates are used in the comparison.
* The unadjusted start date is included, the unadjusted end date is excluded.
*
* @param date the date to check
* @return true if this period contains the date
*/
boolean contains(LocalDate date) {
return !date.isBefore(unadjustedStartDate) && date.isBefore(unadjustedEndDate);
}