下面列出了怎么用java.time.LocalDate的API类实例代码及写法,或者点击链接到github查看源代码。
@ImmutableConstructor
private SimpleDiscountFactors(
Currency currency,
LocalDate valuationDate,
Curve curve) {
ArgChecker.notNull(currency, "currency");
ArgChecker.notNull(valuationDate, "valuationDate");
ArgChecker.notNull(curve, "curve");
curve.getMetadata().getXValueType().checkEquals(
ValueType.YEAR_FRACTION, "Incorrect x-value type for discount curve");
curve.getMetadata().getYValueType().checkEquals(
ValueType.DISCOUNT_FACTOR, "Incorrect y-value type for discount curve");
DayCount dayCount = curve.getMetadata().findInfo(CurveInfoType.DAY_COUNT)
.orElseThrow(() -> new IllegalArgumentException("Incorrect curve metadata, missing DayCount"));
this.currency = currency;
this.valuationDate = valuationDate;
this.curve = curve;
this.dayCount = dayCount;
}
public static CT_DocInfo docInfoCase(){
CT_DocInfo docInfo = new CT_DocInfo();
CustomDatas customDatas = new CustomDatas()
.addCustomData("key1", "value1")
.addCustomData("key2", "value2");
docInfo.randomDocID()
.setTile("Title")
.setAuthor("Cliven")
.setSubject("Subject")
.setAbstract("This is abstract")
.setCreationDate(LocalDate.now().minusDays(1L))
.setModDate(LocalDate.now())
.setDocUsage(DocUsage.Normal)
.setCover(new ST_Loc("./Res/Cover.xml"))
.addKeyword("111")
.addKeyword("222")
.setCreator("ofdrw")
.setCreatorVersion("1.0.0-SNAPSHOT")
.setCustomDatas(customDatas);
return docInfo;
}
@Test
public void test_builder() {
ResolvedCapitalIndexedBond test = sut();
assertThat(test.getCurrency()).isEqualTo(USD);
assertThat(test.getDayCount()).isEqualTo(ACT_ACT_ISDA);
assertThat(test.getStartDate()).isEqualTo(PERIODIC[0].getStartDate());
assertThat(test.getEndDate()).isEqualTo(PERIODIC[3].getEndDate());
assertThat(test.getUnadjustedStartDate()).isEqualTo(PERIODIC[0].getUnadjustedStartDate());
assertThat(test.getUnadjustedEndDate()).isEqualTo(PERIODIC[3].getUnadjustedEndDate());
assertThat(test.getLegalEntityId()).isEqualTo(LEGAL_ENTITY);
assertThat(test.getNominalPayment()).isEqualTo(NOMINAL);
assertThat(test.getNotional()).isEqualTo(NOTIONAL);
assertThat(test.getPeriodicPayments().toArray()).isEqualTo(PERIODIC);
assertThat(test.getSettlementDateOffset()).isEqualTo(SETTLE_OFFSET);
assertThat(test.getYieldConvention()).isEqualTo(US_IL_REAL);
assertThat(test.hasExCouponPeriod()).isFalse();
assertThat(test.getFirstIndexValue()).isEqualTo(RATE_CALC.getFirstIndexValue().getAsDouble());
assertThat(test.findPeriod(PERIODIC[0].getUnadjustedStartDate())).isEqualTo(Optional.of(test.getPeriodicPayments().get(0)));
assertThat(test.findPeriod(LocalDate.MIN)).isEqualTo(Optional.empty());
assertThat(test.findPeriodIndex(PERIODIC[0].getUnadjustedStartDate())).isEqualTo(OptionalInt.of(0));
assertThat(test.findPeriodIndex(PERIODIC[1].getUnadjustedStartDate())).isEqualTo(OptionalInt.of(1));
assertThat(test.findPeriodIndex(LocalDate.MIN)).isEqualTo(OptionalInt.empty());
assertThat(test.calculateSettlementDateFromValuation(date(2015, 6, 30), REF_DATA))
.isEqualTo(SETTLE_OFFSET.adjust(date(2015, 6, 30), REF_DATA));
}
public void test_date_comparator_checkGenerics_LocalDate() {
List<LocalDate> dates = new ArrayList<>();
LocalDate date = LocalDate.of(2013, 1, 1);
// Insert dates in order, no duplicates
dates.add(date.minus(10, ChronoUnit.YEARS));
dates.add(date.minus(1, ChronoUnit.YEARS));
dates.add(date.minus(1, ChronoUnit.MONTHS));
dates.add(date.minus(1, ChronoUnit.WEEKS));
dates.add(date.minus(1, ChronoUnit.DAYS));
dates.add(date);
dates.add(date.plus(1, ChronoUnit.DAYS));
dates.add(date.plus(1, ChronoUnit.WEEKS));
dates.add(date.plus(1, ChronoUnit.MONTHS));
dates.add(date.plus(1, ChronoUnit.YEARS));
dates.add(date.plus(10, ChronoUnit.YEARS));
List<LocalDate> copy = new ArrayList<>(dates);
Collections.shuffle(copy);
Collections.sort(copy, ChronoLocalDate.timeLineOrder());
assertEquals(copy, dates);
assertTrue(ChronoLocalDate.timeLineOrder().compare(copy.get(0), copy.get(1)) < 0);
}
void test_comparisons_LocalDateTime(LocalDate... localDates) {
test_comparisons_LocalDateTime(
localDates,
LocalTime.MIDNIGHT,
LocalTime.of(0, 0, 0, 999999999),
LocalTime.of(0, 0, 59, 0),
LocalTime.of(0, 0, 59, 999999999),
LocalTime.of(0, 59, 0, 0),
LocalTime.of(0, 59, 59, 999999999),
LocalTime.NOON,
LocalTime.of(12, 0, 0, 999999999),
LocalTime.of(12, 0, 59, 0),
LocalTime.of(12, 0, 59, 999999999),
LocalTime.of(12, 59, 0, 0),
LocalTime.of(12, 59, 59, 999999999),
LocalTime.of(23, 0, 0, 0),
LocalTime.of(23, 0, 0, 999999999),
LocalTime.of(23, 0, 59, 0),
LocalTime.of(23, 0, 59, 999999999),
LocalTime.of(23, 59, 0, 0),
LocalTime.of(23, 59, 59, 999999999)
);
}
@Test
void mapping_to_date_field_with_converter() {
ctx = map(LocalDate.of(2000, 1, 1)).using(converter(date -> date.toString(), "empty", "date to string"))
.to(stringField).executeOn(model, model);
doc = documentOf(ctx);
assertThat(doc).percentageValue_DIV().isEmpty();
assertThat(doc).nary_OL().hasSize(0);
assertThat(doc).binary_LI().hasSize(0);
assertThat(doc).nary_LI().hasSize(0);
assertThat(doc).leaf_LI().hasSize(0);
assertThat(doc).when_UL().hasSize(0);
assertThat(doc).binary_UL().hasSize(0);
assertThat(doc).binaryChild_UL().hasSize(0);
assertThat(doc).unary_UL().hasSize(0);
assertThat(doc).tokenWhen_SPAN().hasSize(0);
assertThat(doc).tokenThen_SPAN().hasSize(0);
assertThat(doc).tokenElse_SPAN().hasSize(0);
assertThat(doc).tokenSingleMapping_SPAN().hasSize(1);
assertThat(doc).tokenOperator_SPAN().containsExactly("map", "using", "to");
assertThat(doc).tokenValue_SPAN().containsExactly("2000-01-01", "'date to string'");
assertThat(doc).tokenNary_SPAN().isEmpty();
}
@GET
@Path("winners2")
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed("Subscriber")
public String winners2() {
int remaining = 6;
ArrayList<Integer> numbers = new ArrayList<>();
// If the JWT contains a birthdate claim, use the day of the month as a pick
if (birthdate.isPresent()) {
String bdayString = birthdate.get().getString();
LocalDate bday = LocalDate.parse(bdayString);
numbers.add(bday.getDayOfMonth());
remaining--;
}
// Fill remaining picks with random numbers
while (remaining > 0) {
int pick = (int) Math.rint(64 * Math.random() + 1);
numbers.add(pick);
remaining--;
}
return numbers.toString();
}
@Override
public double getPaymentOffset(final double fixingTime) {
if(getPaymentOffsetCode() == null) {
return paymentOffset;
}
if(paymentOffsets.containsKey(fixingTime)) {
return paymentOffsets.get(fixingTime);
}
else {
/*
* TODO In case paymentDate is relevant for the index modeling, it should be checked
* if the following derivation of paymentDate is accurate (e.g. wo we have a fixingOffset).
* In such a case, this method may be overridden.
*/
final LocalDate referenceDate = getReferenceDate();
final LocalDate fixingDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, fixingTime);
final LocalDate paymentDate = getPaymentBusinessdayCalendar().getAdjustedDate(fixingDate, getPaymentOffsetCode(), getPaymentDateRollConvention());
final double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(referenceDate, paymentDate);
paymentOffsets.put(fixingTime, paymentTime-fixingTime);
return paymentTime-fixingTime;
}
}
void doTest_comparisons_LocalDate(LocalDate... localDates) {
for (int i = 0; i < localDates.length; i++) {
LocalDate a = localDates[i];
for (int j = 0; j < localDates.length; j++) {
LocalDate b = localDates[j];
if (i < j) {
assertTrue(a.compareTo(b) < 0, a + " <=> " + b);
assertEquals(a.isBefore(b), true, a + " <=> " + b);
assertEquals(a.isAfter(b), false, a + " <=> " + b);
assertEquals(a.equals(b), false, a + " <=> " + b);
} else if (i > j) {
assertTrue(a.compareTo(b) > 0, a + " <=> " + b);
assertEquals(a.isBefore(b), false, a + " <=> " + b);
assertEquals(a.isAfter(b), true, a + " <=> " + b);
assertEquals(a.equals(b), false, a + " <=> " + b);
} else {
assertEquals(a.compareTo(b), 0, a + " <=> " + b);
assertEquals(a.isBefore(b), false, a + " <=> " + b);
assertEquals(a.isAfter(b), false, a + " <=> " + b);
assertEquals(a.equals(b), true, a + " <=> " + b);
}
}
}
}
@Test(dataProvider = "resolve_ymaa")
public void test_resolve_ymaa_strict(int y, int m, int w, int d, LocalDate expected, boolean smart, boolean strict) {
Map<TemporalField, Long> fieldValues = new HashMap<>();
fieldValues.put(ChronoField.YEAR, (long) y);
fieldValues.put(ChronoField.MONTH_OF_YEAR, (long) m);
fieldValues.put(ChronoField.ALIGNED_WEEK_OF_MONTH, (long) w);
fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d);
if (strict) {
LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT);
assertEquals(date, expected);
assertEquals(fieldValues.size(), 0);
} else {
try {
IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT);
fail("Should have failed");
} catch (DateTimeException ex) {
// expected
}
}
}
@Test(expected=NullPointerException.class)
public void constructor_nullOffset() throws Throwable {
Constructor<OffsetDateTime> con = OffsetDateTime.class.getDeclaredConstructor(LocalDateTime.class, ZoneOffset.class);
con.setAccessible(true);
try {
con.newInstance(LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30)), null);
} catch (InvocationTargetException ex) {
throw ex.getCause();
}
}
@Test(dataProvider="sampleTimes")
public void test_get_same(int y, int o, int d, int h, int m, int s, int n, ZoneOffset offset) {
LocalDate localDate = LocalDate.of(y, o, d);
LocalTime localTime = LocalTime.of(h, m, s, n);
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
OffsetDateTime a = OffsetDateTime.of(localDateTime, offset);
assertSame(a.getOffset(), offset);
assertSame(a.toLocalDate(), localDate);
assertSame(a.toLocalTime(), localTime);
assertSame(a.toLocalDateTime(), localDateTime);
}
@Test
public void test_firstDayOfNextMonth_leap() {
for (Month month : Month.values()) {
for (int i = 1; i <= month.length(true); i++) {
LocalDate date = date(2008, month, i);
LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfNextMonth().adjustInto(date);
assertEquals(test.getYear(), month == DECEMBER ? 2009 : 2008);
assertEquals(test.getMonth(), month.plus(1));
assertEquals(test.getDayOfMonth(), 1);
}
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
String v = in.nextString();
return SumkDate.of(v, SumkDate.yyyy_MM_dd).toLocalDate();
}
private static int getWeekRange(int wby) {
LocalDate date = LocalDate.of(wby, 1, 1);
// 53 weeks if standard year starts on Thursday, or Wed in a leap year
if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {
return 53;
}
return 52;
}
@Test(dataProvider="samplePlusDaysSymmetry")
public void test_plusDays_symmetry(LocalDate reference) {
for (int days = 0; days < 365 * 8; days++) {
LocalDate t = reference.plusDays(days).plusDays(-days);
assertEquals(t, reference);
t = reference.plusDays(-days).plusDays(days);
assertEquals(t, reference);
}
}
@Test(dataProvider="samples")
public void test_samples_parse_LENIENT(TemporalField field, LocalDate date, long value) {
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field)
.toFormatter().withResolverStyle(ResolverStyle.LENIENT);
LocalDate parsed = LocalDate.parse(Long.toString(value), f);
assertEquals(parsed, date);
}
@Override
public MonetaryRounding getRounding(RoundingQuery roundingQuery) {
LocalDate timestamp = roundingQuery.get(LocalDate.class);
if (roundingQuery.getRoundingName() == null) {
return getRounding(roundingQuery, timestamp, "default");
} else {
return getRounding(roundingQuery, timestamp, roundingQuery.getRoundingName());
}
}
@Override
public boolean hasStornoBeforeDate(IInvoice invoice, LocalDate date){
List<IPayment> zahlungen = invoice.getPayments();
for (IPayment zahlung : zahlungen) {
if (zahlung.getRemark().equals("Storno")) {
if (zahlung.getDate().isBefore(date) || zahlung.getDate().equals(date)) {
return true;
}
}
}
return false;
}
@Inject
public InvoicePayment createInvoicePayment(
Invoice invoice,
BigDecimal amount,
LocalDate paymentDate,
Currency currency,
PaymentMode paymentMode,
int typeSelect);
public Duration yearsAndMonthsDuration(ZonedDateTime from, LocalDate to) {
try {
return this.durationLib.yearsAndMonthsDuration(from, to);
} catch (Exception e) {
String message = String.format("yearsAndMonthsDuration(%s, %s)", from, to);
logError(message, e);
return null;
}
}
@Override
public double explainRate(
OvernightAveragedRateComputation computation,
LocalDate startDate,
LocalDate endDate,
RatesProvider provider,
ExplainMapBuilder builder) {
double rate = rate(computation, startDate, endDate, provider);
builder.put(ExplainKey.COMBINED_RATE, rate);
return rate;
}
private WeatherReport getFakeWeatherReport(String location, LocalDate date) {
Random rand = ThreadLocalRandom.current();
Stopwatch stopwatch = Stopwatch.createStarted();
try {
Thread.sleep(500 + rand.nextInt(500));
resourceCallService.addCall("Fake Webservice call", ResourceType.WEB_SERVICE, location, stopwatch.elapsed(TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
// ignore
}
int min = -30 + rand.nextInt(60);
int max = min + rand.nextInt(15);
String summary = WEATHERS[rand.nextInt(WEATHERS.length)];
String icon = summary.toLowerCase(Locale.US);
return new WeatherReport(date, location, summary, icon, min, max);
}
@Test
public void selectDate() throws ExecutionException, InterruptedException, TimeoutException {
try (Session session = ds.getSession()) {
CompletionStage<LocalDate> idF = session.<LocalDate>rowOperation("select '2018-04-29 20:55:57.692132'::date as t")
.collect(singleCollector(LocalDate.class))
.submit()
.getCompletionStage();
assertEquals(LocalDate.of(2018, 4, 29), get10(idF));
}
}
@Override
protected void doProcess(final JCas jCas) throws AnalysisEngineProcessException {
final DocumentAnnotation da = getDocumentAnnotation(jCas);
final String source = da.getSourceUri();
final Matcher matcher = pattern.matcher(source);
if (matcher.matches()) {
try {
final int y = Integer.parseInt(matcher.group("year"));
final int m = Integer.parseInt(matcher.group("month"));
final int d = Integer.parseInt(matcher.group("day"));
if (m >= 1 && m <= 12 && d >= 1 && d <= 31) {
// This will check if its' actually valid (31 Feb) it's actualy valid date...
final LocalDate date = LocalDate.of(y, m, d);
final long ts = date.atStartOfDay().atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
da.setTimestamp(ts);
}
} catch (final Exception e) {
// Do nothing.. not a valid source path...
getMonitor().warn("Cant parse date from source uri {} ", source, e);
}
}
}
@Test
public void testNewBoundedCategoryWithExistingBoundedAndPendingTicket() {
List<TicketCategoryModification> categories = Collections.singletonList(
new TicketCategoryModification(null, "default", AVAILABLE_SEATS,
new DateTimeModification(LocalDate.now(), LocalTime.now()),
new DateTimeModification(LocalDate.now(), LocalTime.now()),
DESCRIPTION, BigDecimal.TEN, false, "", false, null, null, null, null, null, 0, null, null, AlfioMetadata.empty()));
Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository);
Event event = pair.getLeft();
String username = pair.getRight();
assertEquals(Integer.valueOf(AVAILABLE_SEATS), ticketRepository.countFreeTicketsForUnbounded(event.getId()));
TicketReservationModification trm = new TicketReservationModification();
trm.setAmount(1);
trm.setTicketCategoryId(ticketCategoryRepository.findAllTicketCategories(event.getId()).get(0).getId());
TicketReservationWithOptionalCodeModification reservation = new TicketReservationWithOptionalCodeModification(trm, Optional.empty());
ticketReservationManager.createTicketReservation(event, Collections.singletonList(reservation), Collections.emptyList(),
DateUtils.addDays(new Date(), 1), Optional.empty(), Locale.ENGLISH, false);
TicketCategoryModification tcm = new TicketCategoryModification(null, "new", 1,
DateTimeModification.fromZonedDateTime(ZonedDateTime.now()),
DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1)),
Collections.emptyMap(), BigDecimal.TEN, false, "", true, null, null, null, null, null, 0, null, null, AlfioMetadata.empty());
Result<Integer> insertResult = eventManager.insertCategory(event, tcm, username);
assertTrue(insertResult.isSuccess());
Integer categoryID = insertResult.getData();
tcm = new TicketCategoryModification(categoryID, tcm.getName(), AVAILABLE_SEATS,
tcm.getInception(), tcm.getExpiration(), tcm.getDescription(), tcm.getPrice(), false, "", true, null, null, null, null, null, 0, null, null, AlfioMetadata.empty());
Result<TicketCategory> result = eventManager.updateCategory(categoryID, event, tcm, username);
assertFalse(result.isSuccess());
}
@Test
@UseDataProvider("data_weekFields")
public void test_fieldRanges(DayOfWeek firstDayOfWeek, int minDays) {
WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
TemporalField womField = weekDef.weekOfMonth();
TemporalField woyField = weekDef.weekOfYear();
LocalDate day = LocalDate.of(2012, 11, 30);
LocalDate endDay = LocalDate.of(2013, 1, 2);
while (day.isBefore(endDay)) {
LocalDate last = day.with(DAY_OF_MONTH, day.lengthOfMonth());
int lastWOM = last.get(womField);
LocalDate first = day.with(DAY_OF_MONTH, 1);
int firstWOM = first.get(womField);
ValueRange rangeWOM = day.range(womField);
assertEquals("Range min should be same as WeekOfMonth for first day of month: "
+ first + ", " + weekDef, rangeWOM.getMinimum(), firstWOM);
assertEquals("Range max should be same as WeekOfMonth for last day of month: "
+ last + ", " + weekDef, rangeWOM.getMaximum(), lastWOM);
last = day.with(DAY_OF_YEAR, day.lengthOfYear());
int lastWOY = last.get(woyField);
first = day.with(DAY_OF_YEAR, 1);
int firstWOY = first.get(woyField);
ValueRange rangeWOY = day.range(woyField);
assertEquals("Range min should be same as WeekOfYear for first day of Year: "
+ day + ", " + weekDef, rangeWOY.getMinimum(), firstWOY);
assertEquals("Range max should be same as WeekOfYear for last day of Year: "
+ day + ", " + weekDef, rangeWOY.getMaximum(), lastWOY);
day = day.plusDays(1);
}
}
@Test(dataProvider="sampleMinusDaysSymmetry")
public void test_minusDays_symmetry(LocalDate reference) {
for (int days = 0; days < 365 * 8; days++) {
LocalDate t = reference.minusDays(days).minusDays(-days);
assertEquals(t, reference);
t = reference.minusDays(-days).minusDays(days);
assertEquals(t, reference);
}
}
@Override
public DatedParameterMetadata metadata(LocalDate valuationDate, ReferenceData refData) {
LocalDate nodeDate = date(valuationDate, refData);
if (date.isFixed()) {
return LabelDateParameterMetadata.of(nodeDate, label);
}
Tenor tenor = Tenor.of(template.getPeriodToFar());
return TenorDateParameterMetadata.of(nodeDate, tenor, label);
}
@DataProvider(name="sampleMinusDaysSymmetry")
Object[][] provider_sampleMinusDaysSymmetry() {
return new Object[][] {
{LocalDate.of(-1, 1, 1)},
{LocalDate.of(-1, 2, 28)},
{LocalDate.of(-1, 3, 1)},
{LocalDate.of(-1, 12, 31)},
{LocalDate.of(0, 1, 1)},
{LocalDate.of(0, 2, 28)},
{LocalDate.of(0, 2, 29)},
{LocalDate.of(0, 3, 1)},
{LocalDate.of(0, 12, 31)},
{LocalDate.of(2007, 1, 1)},
{LocalDate.of(2007, 2, 28)},
{LocalDate.of(2007, 3, 1)},
{LocalDate.of(2007, 12, 31)},
{LocalDate.of(2008, 1, 1)},
{LocalDate.of(2008, 2, 28)},
{LocalDate.of(2008, 2, 29)},
{LocalDate.of(2008, 3, 1)},
{LocalDate.of(2008, 12, 31)},
{LocalDate.of(2099, 1, 1)},
{LocalDate.of(2099, 2, 28)},
{LocalDate.of(2099, 3, 1)},
{LocalDate.of(2099, 12, 31)},
{LocalDate.of(2100, 1, 1)},
{LocalDate.of(2100, 2, 28)},
{LocalDate.of(2100, 3, 1)},
{LocalDate.of(2100, 12, 31)},
};
}