下面列出了java.time.LocalDate#parse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test(dataProvider="weekFields")
public void test_parse_resolve_localizedWomDow(DayOfWeek firstDayOfWeek, int minDays) {
LocalDate date = LocalDate.of(2012, 12, 15);
WeekFields week = WeekFields.of(firstDayOfWeek, minDays);
TemporalField dowField = week.dayOfWeek();
TemporalField womField = week.weekOfMonth();
for (int i = 1; i <= 15; i++) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(YEAR).appendLiteral(':')
.appendValue(MONTH_OF_YEAR).appendLiteral(':')
.appendValue(womField).appendLiteral(':')
.appendValue(dowField).toFormatter();
String str = date.getYear() + ":" + date.getMonthValue() + ":" +
date.get(womField) + ":" + date.get(dowField);
LocalDate parsed = LocalDate.parse(str, f);
assertEquals(parsed, date, " :: " + str + " " + i);
date = date.plusDays(1);
}
}
public static LocalDateTime parseDate(String date) {
Objects.requireNonNull(date, "date");
for (DateTimeFormatter formatter : DATE_FORMATTERS) {
try {
// equals ISO_LOCAL_DATE
if (formatter.equals(DATE_FORMATTERS.get(2))) {
LocalDate localDate = LocalDate.parse(date, formatter);
return localDate.atStartOfDay();
} else {
return LocalDateTime.parse(date, formatter);
}
} catch (java.time.format.DateTimeParseException ignored) {
}
}
return null;
}
@Test(dataProvider="LocalWeekBasedYearPatterns")
public void test_parse_WeekBasedYear(String pattern, String text, int pos, int expectedPos, LocalDate expectedValue) {
ParsePosition ppos = new ParsePosition(pos);
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder().appendPattern(pattern);
DateTimeFormatter dtf = b.toFormatter(locale);
TemporalAccessor parsed = dtf.parseUnresolved(text, ppos);
if (ppos.getErrorIndex() != -1) {
assertEquals(ppos.getErrorIndex(), expectedPos);
} else {
WeekFields weekDef = WeekFields.of(locale);
assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position");
assertEquals(parsed.isSupported(weekDef.dayOfWeek()), pattern.indexOf('e') >= 0);
assertEquals(parsed.isSupported(weekDef.weekOfWeekBasedYear()), pattern.indexOf('w') >= 0);
assertEquals(parsed.isSupported(weekDef.weekBasedYear()), pattern.indexOf('Y') >= 0);
// ensure combination resolves into a date
LocalDate result = LocalDate.parse(text, dtf);
assertEquals(result, expectedValue, "LocalDate incorrect for " + pattern + ", weekDef: " + weekDef);
}
}
@Test(dataProvider="weekFields")
public void test_parse_resolve_localizedWoy_lenient(DayOfWeek firstDayOfWeek, int minDays) {
LocalDate date = LocalDate.of(2012, 12, 15);
WeekFields week = WeekFields.of(firstDayOfWeek, minDays);
TemporalField woyField = week.weekOfYear();
for (int i = 1; i <= 60; i++) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(YEAR).appendLiteral(':')
.appendValue(woyField).appendLiteral(':')
.appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(LENIENT);
int woy = date.get(woyField);
int dow = date.get(DAY_OF_WEEK);
for (int j = woy - 60; j < woy + 60; j++) {
String str = date.getYear() + ":" + j + ":" + dow;
LocalDate parsed = LocalDate.parse(str, f);
assertEquals(parsed, date.plusWeeks(j - woy), " ::" + str + ": :" + i + "::" + j);
}
date = date.plusDays(1);
}
}
@Test(dataProvider="sampleToString")
public void factory_parse_validText(int y, int m, int d, String parsable) {
LocalDate t = LocalDate.parse(parsable);
assertNotNull(t, parsable);
assertEquals(t.getYear(), y, parsable);
assertEquals(t.getMonth().getValue(), m, parsable);
assertEquals(t.getDayOfMonth(), d, parsable);
}
@Test(dataProvider="week")
public void test_parse_weeks_LENIENT(LocalDate date, DayOfWeek dow, int week, int wby) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral('-')
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral('-')
.appendValue(DAY_OF_WEEK)
.toFormatter().withResolverStyle(ResolverStyle.LENIENT);
LocalDate parsed = LocalDate.parse(wby + "-" + week + "-" + dow.getValue(), f);
assertEquals(parsed, date);
}
@Test(dataProvider = "parseLenientWeek", expectedExceptions = DateTimeParseException.class)
public void test_parse_parseLenientWeek_STRICT(String str, LocalDate expected, boolean smart) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':')
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral(':')
.appendValue(DAY_OF_WEEK)
.toFormatter().withResolverStyle(ResolverStyle.STRICT);
LocalDate.parse(str, f);
}
@Test(dataProvider = "parseLenientQuarter")
public void test_parse_parseLenientQuarter_LENIENT(String str, LocalDate expected, boolean smart) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(YEAR).appendLiteral(':')
.appendValue(IsoFields.QUARTER_OF_YEAR).appendLiteral(':')
.appendValue(IsoFields.DAY_OF_QUARTER)
.toFormatter().withResolverStyle(ResolverStyle.LENIENT);
LocalDate parsed = LocalDate.parse(str, f);
assertEquals(parsed, expected);
}
@Test(dataProvider="week")
public void test_parse_weeks_SMART(LocalDate date, DayOfWeek dow, int week, int wby) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral('-')
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral('-')
.appendValue(DAY_OF_WEEK)
.toFormatter().withResolverStyle(ResolverStyle.SMART);
LocalDate parsed = LocalDate.parse(wby + "-" + week + "-" + dow.getValue(), f);
assertEquals(parsed, date);
}
@Test(dataProvider = "parseLenientQuarter")
public void test_parse_parseLenientQuarter_LENIENT(String str, LocalDate expected, boolean smart) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(YEAR).appendLiteral(':')
.appendValue(IsoFields.QUARTER_OF_YEAR).appendLiteral(':')
.appendValue(IsoFields.DAY_OF_QUARTER)
.toFormatter().withResolverStyle(ResolverStyle.LENIENT);
LocalDate parsed = LocalDate.parse(str, f);
assertEquals(parsed, expected);
}
@Override
public LocalDate unmarshal( String localDateString ) throws Exception {
if ( localDateString == null ) {
return null;
}
try {
return LocalDate.parse( localDateString );
} catch ( DateTimeException e ) {
throw new IllegalStateException( "Failed to convert string (" + localDateString + ") to type ("
+ LocalDate.class.getName() + ")." );
}
}
@Test(dataProvider = "parseLenientWeek")
public void test_parse_parseLenientWeek_LENIENT(String str, LocalDate expected, boolean smart) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':')
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral(':')
.appendValue(DAY_OF_WEEK)
.toFormatter().withResolverStyle(ResolverStyle.LENIENT);
LocalDate parsed = LocalDate.parse(str, f);
assertEquals(parsed, expected);
}
@Override
public LocalDate unmarshal(String string) throws Exception{
return LocalDate.parse(string, formatter);
}
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_formatter_nullText() {
DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d");
LocalDate.parse((String) null, f);
}
@Test(expectedExceptions=DateTimeParseException.class)
public void factory_parse_invalidValue() {
LocalDate.parse("2008-06-31");
}
@Test
public void testLeapYearInDateUsingJavaTimeYear () {
LocalDate date = LocalDate.parse("2020-01-05", DateTimeFormatter.ISO_LOCAL_DATE);
Assert.assertTrue(Year.from(date).isLeap());
}
/**
* {@inheritDoc}
*/
@Override
protected LocalDate parse(final String string) {
return LocalDate.parse(string);
}
/**
* ScheduleFromPeriods generation with futureCodes (in the format DEC17). Futures are assumed to expire on the third wednesday in the respective month.
*
* @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0.
* @param futureCode Future code in the format DEC17
* @param startOffsetString The start date as an offset from the spotDate (build from tradeDate and spotOffsetDays) entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc.
* @param maturityString The end date of the last period entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc.
* @param frequency The frequency (as String).
* @param daycountConvention The daycount convention (as String).
* @param shortPeriodConvention If short period exists, have it first or last (as String).
* @param dateRollConvention Adjustment to be applied to the all dates (as String).
* @param businessdayCalendar Business day calendar (holiday calendar) to be used for date roll adjustment.
* @param fixingOffsetDays Number of business days to be added to period start to get the fixing date.
* @param paymentOffsetDays Number of business days to be added to period end to get the payment date.
* @return The corresponding schedule
*/
public static Schedule createScheduleFromConventions(
final LocalDate referenceDate,
final String futureCode,
final String startOffsetString,
final String maturityString,
final String frequency,
final String daycountConvention,
final String shortPeriodConvention,
final String dateRollConvention,
final BusinessdayCalendar businessdayCalendar,
final int fixingOffsetDays,
final int paymentOffsetDays
)
{
final int futureExpiryYearsShort = Integer.parseInt(futureCode.substring(futureCode.length()-2));
final String futureExpiryMonthsString = futureCode.substring(0,futureCode.length()-2);
final DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd/MMM/yy").toFormatter(Locale.ENGLISH);
final String futureExpiryString = "01/" + futureExpiryMonthsString + "/" + futureExpiryYearsShort;
LocalDate futureExpiryDate;
try{
futureExpiryDate = LocalDate.parse(futureExpiryString, formatter);
} catch(final DateTimeParseException e) {
throw new IllegalArgumentException("Error when parsing futureCode " + futureCode + ". Must be of format MMMYY with english month format (e.g. DEC17)");
}
// get third wednesday in month, adjust with following if no busday
while(!futureExpiryDate.getDayOfWeek().equals(DayOfWeek.WEDNESDAY)) {
futureExpiryDate = futureExpiryDate.plusDays(1);
}
futureExpiryDate = futureExpiryDate.plusWeeks(2);
futureExpiryDate = businessdayCalendar.getAdjustedDate(futureExpiryDate, startOffsetString, DateRollConvention.FOLLOWING); // adjust to the next good busday
final LocalDate maturityDate = businessdayCalendar.getDateFromDateAndOffsetCode(futureExpiryDate, maturityString);
return createScheduleFromConventions(
referenceDate,
futureExpiryDate,
maturityDate,
Frequency.valueOf(frequency.replace("/", "_").toUpperCase()),
DaycountConvention.getEnum(daycountConvention),
ShortPeriodConvention.valueOf(shortPeriodConvention.replace("/", "_").toUpperCase()),
DateRollConvention.getEnum(dateRollConvention),
businessdayCalendar,
fixingOffsetDays,
paymentOffsetDays
);
}
public LocalDate getDate() {
return LocalDate.parse(getText("dateTextId"),
DateTimeFormatter.ofPattern("MM/dd/yyyy"));
}
/**
* 把字符串转换为LocalDate类型
* @param dateStr
* @param pattern
* @return
*/
public static LocalDate stringToLocalDate(String dateStr, DatePattern pattern){
final DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern.getPattern());
return LocalDate.parse(dateStr, df);
}