下面列出了怎么用java.time.chrono.ChronoLocalDate的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns the week of week-based-year for the temporal.
* The week can be part of the previous year, the current year,
* or the next year depending on the week start and minimum number
* of days.
* @param temporal a date of any chronology
* @return the week of the year
* @see #localizedWeekBasedYear(java.time.temporal.TemporalAccessor)
*/
private int localizedWeekOfWeekBasedYear(TemporalAccessor temporal) {
int dow = localizedDayOfWeek(temporal);
int doy = temporal.get(DAY_OF_YEAR);
int offset = startOfWeekOffset(doy, dow);
int week = computeWeek(offset, doy);
if (week == 0) {
// Day is in end of week of previous year
// Recompute from the last day of the previous year
ChronoLocalDate date = Chronology.from(temporal).date(temporal);
date = date.minus(doy, DAYS); // Back down into previous year
return localizedWeekOfWeekBasedYear(date);
} else if (week > 50) {
// If getting close to end of year, use higher precision logic
// Check if date of year is in partial week associated with next year
ValueRange dayRange = temporal.range(DAY_OF_YEAR);
int yearLen = (int)dayRange.getMaximum();
int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());
if (week >= newYearWeek) {
// Overlaps with week of following year; reduce to week in following year
week = week - newYearWeek + 1;
}
}
return week;
}
@Test(dataProvider="calendars")
public void test_badPlusTemporalUnitChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoLocalDate date = chrono.date(refDate);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoLocalDate date2 = chrono2.date(refDate);
TemporalUnit adjuster = new FixedTemporalUnit(date2);
if (chrono != chrono2) {
try {
date.plus(1, adjuster);
Assert.fail("TemporalUnit.doAdd plus should have thrown a ClassCastException" + date.getClass()
+ ", can not be cast to " + date2.getClass());
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoLocalDate result = date.plus(1, adjuster);
assertEquals(result, date2, "WithAdjuster failed to replace date");
}
}
}
@Test(dataProvider="ReducedWithChrono")
public void test_reducedWithChronoYearOfEra(ChronoLocalDate date) {
Chronology chrono = date.getChronology();
DateTimeFormatter df
= new DateTimeFormatterBuilder().appendValueReduced(YEAR_OF_ERA, 2, 2, LocalDate.of(2000, 1, 1))
.toFormatter()
.withChronology(chrono);
int expected = date.get(YEAR_OF_ERA);
String input = df.format(date);
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = df.parseUnresolved(input, pos);
int actual = parsed.get(YEAR_OF_ERA);
assertEquals(actual, expected,
String.format("Wrong date parsed, chrono: %s, input: %s",
chrono, input));
}
@Test(dataProvider="ReducedWithChrono")
public void test_reducedWithChronoYear(ChronoLocalDate date) {
Chronology chrono = date.getChronology();
DateTimeFormatter df
= new DateTimeFormatterBuilder().appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
.toFormatter()
.withChronology(chrono);
int expected = date.get(YEAR);
String input = df.format(date);
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = df.parseUnresolved(input, pos);
int actual = parsed.get(YEAR);
assertEquals(actual, expected,
String.format("Wrong date parsed, chrono: %s, input: %s",
chrono, input));
}
@Test(dataProvider="ReducedWithChrono")
public void test_reducedWithChronoYearOfEra(ChronoLocalDate date) {
Chronology chrono = date.getChronology();
DateTimeFormatter df
= new DateTimeFormatterBuilder().appendValueReduced(YEAR_OF_ERA, 2, 2, LocalDate.of(2000, 1, 1))
.toFormatter()
.withChronology(chrono);
int expected = date.get(YEAR_OF_ERA);
String input = df.format(date);
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = df.parseUnresolved(input, pos);
int actual = parsed.get(YEAR_OF_ERA);
assertEquals(actual, expected,
String.format("Wrong date parsed, chrono: %s, input: %s",
chrono, input));
}
/**
* Constructor.
*
* @param field the field to format, validated not null
* @param minWidth the minimum field width, from 1 to 10
* @param maxWidth the maximum field width, from 1 to 10
* @param baseValue the base value
* @param baseDate the base date
*/
ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth,
int baseValue, ChronoLocalDate baseDate) {
this(field, minWidth, maxWidth, baseValue, baseDate, 0);
if (minWidth < 1 || minWidth > 10) {
throw new IllegalArgumentException("The minWidth must be from 1 to 10 inclusive but was " + minWidth);
}
if (maxWidth < 1 || maxWidth > 10) {
throw new IllegalArgumentException("The maxWidth must be from 1 to 10 inclusive but was " + minWidth);
}
if (maxWidth < minWidth) {
throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
maxWidth + " < " + minWidth);
}
if (baseDate == null) {
if (field.range().isValidValue(baseValue) == false) {
throw new IllegalArgumentException("The base value must be within the range of the field");
}
if ((((long) baseValue) + EXCEED_POINTS[maxWidth]) > Integer.MAX_VALUE) {
throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int");
}
}
}
@Test(dataProvider="mapTextLookup")
public void test_appendText_mapTextLookup(ChronoLocalDate date, Locale locale) {
final String firstYear = "firstYear";
final String firstMonth = "firstMonth";
final String firstYearMonth = firstYear + firstMonth;
final long first = 1L;
Map<Long, String> yearMap = new HashMap<Long, String>();
yearMap.put(first, firstYear);
Map<Long, String> monthMap = new HashMap<Long, String>();
monthMap.put(first, firstMonth);
DateTimeFormatter formatter = builder
.appendText(ChronoField.YEAR_OF_ERA, yearMap)
.appendText(ChronoField.MONTH_OF_YEAR, monthMap)
.toFormatter(locale)
.withResolverStyle(ResolverStyle.STRICT);
assertEquals(date.format(formatter), firstYearMonth);
TemporalAccessor ta = formatter.parse(firstYearMonth);
assertEquals(ta.getLong(ChronoField.YEAR_OF_ERA), first);
assertEquals(ta.getLong(ChronoField.MONTH_OF_YEAR), first);
}
@Test(dataProvider="calendars")
public void test_badMinusAdjusterChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoLocalDate date = chrono.date(refDate);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoLocalDate date2 = chrono2.date(refDate);
TemporalAmount adjuster = new FixedAdjuster(date2);
if (chrono != chrono2) {
try {
date.minus(adjuster);
Assert.fail("WithAdjuster should have thrown a ClassCastException");
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoLocalDate result = date.minus(adjuster);
assertEquals(result, date2, "WithAdjuster failed to replace date");
}
}
}
@Test(dataProvider="calendars")
public void test_badMinusTemporalUnitChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoLocalDate date = chrono.date(refDate);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoLocalDate date2 = chrono2.date(refDate);
TemporalUnit adjuster = new FixedTemporalUnit(date2);
if (chrono != chrono2) {
try {
date.minus(1, adjuster);
Assert.fail("TemporalUnit.doAdd minus should have thrown a ClassCastException" + date.getClass()
+ ", can not be cast to " + date2.getClass());
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoLocalDate result = date.minus(1, adjuster);
assertEquals(result, date2, "WithAdjuster failed to replace date");
}
}
}
@Override
public ChronoLocalDate resolve(
Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {
Long yearLong = fieldValues.get(YEAR);
Long qoyLong = fieldValues.get(QUARTER_OF_YEAR);
if (yearLong == null || qoyLong == null) {
return null;
}
int y = YEAR.checkValidIntValue(yearLong); // always validate
long doq = fieldValues.get(DAY_OF_QUARTER);
ensureIso(partialTemporal);
LocalDate date;
if (resolverStyle == ResolverStyle.LENIENT) {
date = LocalDate.of(y, 1, 1).plusMonths(Math.multiplyExact(Math.subtractExact(qoyLong, 1), 3));
doq = Math.subtractExact(doq, 1);
} else {
int qoy = QUARTER_OF_YEAR.range().checkValidIntValue(qoyLong, QUARTER_OF_YEAR); // validated
date = LocalDate.of(y, ((qoy - 1) * 3) + 1, 1);
if (doq < 1 || doq > 90) {
if (resolverStyle == ResolverStyle.STRICT) {
rangeRefinedBy(date).checkValidValue(doq, this); // only allow exact range
} else { // SMART
range().checkValidValue(doq, this); // allow 1-92 rolling into next quarter
}
}
doq--;
}
fieldValues.remove(this);
fieldValues.remove(YEAR);
fieldValues.remove(QUARTER_OF_YEAR);
return date.plusDays(doq);
}
public <D extends ChronoLocalDate> void test_date_checkGenerics_genericsMethod_withType() {
Chronology chrono = ThaiBuddhistChronology.INSTANCE;
@SuppressWarnings("unchecked")
D date = (D) chrono.dateNow();
date = processOK(date);
// date = processClassOK(ThaiBuddhistDate.class); // does not compile (correct)
date = dateSupplier();
// date = processWeird(date); // does not compile (correct)
// date = processClassWeird(ThaiBuddhistDate.class); // does not compile (correct)
}
@Test
public void test_IsoChronology_dateYearDay() {
Chronology chrono = Chronology.of("ISO");
ChronoLocalDate date1 = chrono.dateYearDay(IsoEra.CE, 5, 60);
ChronoLocalDate date2 = chrono.date(IsoEra.CE, 5, 3, 1);
assertEquals(date1, IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60));
assertEquals(date2, IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60));
}
@Test(expectedExceptions = DateTimeParseException.class)
public void test_fieldResolvesToChronoLocalDate_overrideChrono_wrongChrono() {
ChronoLocalDate cld = ThaiBuddhistChronology.INSTANCE.dateNow();
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cld)).toFormatter();
f = f.withChronology(MinguoChronology.INSTANCE);
f.parse("1234567890");
}
@Test(dataProvider="calendars", expectedExceptions=DateTimeException.class)
public void test_addTo_wrongChrono(Chronology chrono) {
ChronoPeriod period = chrono.period(1, 2, 3);
ChronoLocalDate isoDate = LocalDate.of(2000, 1, 1);
ChronoLocalDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(2000, 1, 1);
// one of these two will fail
period.addTo(isoDate);
period.addTo(thaiDate);
}
@Test(dataProvider="calendars")
private void test_serialization_format(ChronoLocalDate date, int dateType) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (DataOutputStream dos = new DataOutputStream(baos) ) {
dos.writeByte(dateType);
dos.writeInt(date.get(YEAR));
dos.writeByte(date.get(MONTH_OF_YEAR));
dos.writeByte(date.get(DAY_OF_MONTH));
}
byte[] bytes = baos.toByteArray();
assertSerializedBySer(date, bytes);
}
/**
* Return a new week-based-year date of the Chronology, year, week-of-year,
* and dow of week.
* @param chrono The chronology of the new date
* @param yowby the year of the week-based-year
* @param wowby the week of the week-based-year
* @param dow the day of the week
* @return a ChronoLocalDate for the requested year, week of year, and day of week
*/
private ChronoLocalDate ofWeekBasedYear(Chronology chrono,
int yowby, int wowby, int dow) {
ChronoLocalDate date = chrono.date(yowby, 1, 1);
int ldow = localizedDayOfWeek(date);
int offset = startOfWeekOffset(1, ldow);
// Clamp the week of year to keep it in the same year
int yearLen = date.lengthOfYear();
int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());
wowby = Math.min(wowby, newYearWeek - 1);
int days = -offset + (dow - 1) + (wowby - 1) * 7;
return date.plus(days, DAYS);
}
@Test
public void test_TestServiceLoader() {
Chronology chrono = Chronology.of("Coptic");
ChronoLocalDate copticDate = chrono.date(1729, 4, 27);
LocalDate ld = LocalDate.from(copticDate);
assertEquals(ld, LocalDate.of(2013, 1, 5), "CopticDate does not match LocalDate");
}
@Test
public void test_chronoFields() {
ChronoLocalDate hdate = HijrahChronology.INSTANCE.date(1434, 6, 28);
assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), 3);
assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), 7);
assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_MONTH), 4);
assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_YEAR), 25);
assertEquals(hdate.get(ChronoField.ERA), 1);
assertEquals(hdate.get(ChronoField.YEAR_OF_ERA), 1434);
assertEquals(hdate.get(ChronoField.MONTH_OF_YEAR), 6);
assertEquals(hdate.get(ChronoField.DAY_OF_MONTH), 28);
assertEquals(hdate.get(ChronoField.DAY_OF_WEEK), 3);
assertEquals(hdate.get(ChronoField.DAY_OF_YEAR), 175);
}
@Override
public ChronoLocalDate resolve(
Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {
long value = fieldValues.remove(this);
Chronology chrono = Chronology.from(partialTemporal);
if (resolverStyle == ResolverStyle.LENIENT) {
return chrono.dateEpochDay(Math.subtractExact(value, offset));
}
range().checkValidValue(value, this);
return chrono.dateEpochDay(value - offset);
}
@Test(dataProvider="calendars")
public void test_addTo(Chronology chrono) {
ChronoPeriod period = chrono.period(1, 2, 3);
ChronoLocalDate date = chrono.dateNow();
Temporal result = period.addTo(date);
assertEquals(result, date.plus(14, MONTHS).plus(3, DAYS));
}
@Test
public void test_IsoChronology_dateYearDay() {
Chronology chrono = Chronology.of("ISO");
ChronoLocalDate date1 = chrono.dateYearDay(IsoEra.CE, 5, 60);
ChronoLocalDate date2 = chrono.date(IsoEra.CE, 5, 3, 1);
assertEquals(date1, IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60));
assertEquals(date2, IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60));
}
/**
* Compute the number of days from the Epoch and compute the date from the number of days.
*/
@Test(dataProvider = "calendarNameAndType")
public void test_epoch(String name, String alias) {
Chronology chrono = Chronology.of(name); // a chronology. In practice this is rarely hardcoded
ChronoLocalDate date1 = chrono.dateNow();
long epoch1 = date1.getLong(ChronoField.EPOCH_DAY);
ChronoLocalDate date2 = date1.with(ChronoField.EPOCH_DAY, epoch1);
assertEquals(date1, date2, "Date from epoch day is not same date: " + date1 + " != " + date2);
long epoch2 = date1.getLong(ChronoField.EPOCH_DAY);
assertEquals(epoch1, epoch2, "Epoch day not the same: " + epoch1 + " != " + epoch2);
}
@Test
public void test_chronoFields() {
ChronoLocalDate hdate = HijrahChronology.INSTANCE.date(1434, 6, 28);
assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), 3);
assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), 7);
assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_MONTH), 4);
assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_YEAR), 25);
assertEquals(hdate.get(ChronoField.ERA), 1);
assertEquals(hdate.get(ChronoField.YEAR_OF_ERA), 1434);
assertEquals(hdate.get(ChronoField.MONTH_OF_YEAR), 6);
assertEquals(hdate.get(ChronoField.DAY_OF_MONTH), 28);
assertEquals(hdate.get(ChronoField.DAY_OF_WEEK), 3);
assertEquals(hdate.get(ChronoField.DAY_OF_YEAR), 175);
}
@Test
public void test_chronoFields() {
ChronoLocalDate hdate = HijrahChronology.INSTANCE.date(1434, 6, 28);
assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), 3);
assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), 7);
assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_MONTH), 4);
assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_YEAR), 25);
assertEquals(hdate.get(ChronoField.ERA), 1);
assertEquals(hdate.get(ChronoField.YEAR_OF_ERA), 1434);
assertEquals(hdate.get(ChronoField.MONTH_OF_YEAR), 6);
assertEquals(hdate.get(ChronoField.DAY_OF_MONTH), 28);
assertEquals(hdate.get(ChronoField.DAY_OF_WEEK), 3);
assertEquals(hdate.get(ChronoField.DAY_OF_YEAR), 175);
}
@Test
public void test_HijrahChronology_dateYearDay() {
Chronology chrono = Chronology.of("Hijrah");
ChronoLocalDate date1 = chrono.dateYearDay(HijrahEra.AH, 1434, 178);
ChronoLocalDate date2 = chrono.date(HijrahEra.AH, 1434, 7, 1);
assertEquals(date1, HijrahChronology.INSTANCE.dateYearDay(HijrahEra.AH, 1434, 178));
assertEquals(date2, HijrahChronology.INSTANCE.dateYearDay(HijrahEra.AH, 1434, 178));
}
@Test
public void test_chronoPackageExample() {
// Print the Thai Buddhist date
ChronoLocalDate now1 = Chronology.of("ThaiBuddhist").dateNow();
int day = now1.get(ChronoField.DAY_OF_MONTH);
int dow = now1.get(ChronoField.DAY_OF_WEEK);
int month = now1.get(ChronoField.MONTH_OF_YEAR);
int year = now1.get(ChronoField.YEAR);
System.out.printf(" Today is %s %s %d-%s-%d%n", now1.getChronology().getId(),
dow, day, month, year);
// Enumerate the list of available calendars and print today for each
Set<Chronology> chronos = Chronology.getAvailableChronologies();
for (Chronology chrono : chronos) {
ChronoLocalDate date = chrono.dateNow();
System.out.printf(" %20s: %s%n", chrono.getId(), date.toString());
}
// Print today's date and the last day of the year for the Thai Buddhist Calendar.
ChronoLocalDate first = now1
.with(ChronoField.DAY_OF_MONTH, 1)
.with(ChronoField.MONTH_OF_YEAR, 1);
ChronoLocalDate last = first
.plus(1, ChronoUnit.YEARS)
.minus(1, ChronoUnit.DAYS);
System.out.printf(" %s: 1st of year: %s; end of year: %s%n", last.getChronology().getId(),
first, last);
}
/**
* Return a new week-based-year date of the Chronology, year, week-of-year,
* and dow of week.
* @param chrono The chronology of the new date
* @param yowby the year of the week-based-year
* @param wowby the week of the week-based-year
* @param dow the day of the week
* @return a ChronoLocalDate for the requested year, week of year, and day of week
*/
private ChronoLocalDate ofWeekBasedYear(Chronology chrono,
int yowby, int wowby, int dow) {
ChronoLocalDate date = chrono.date(yowby, 1, 1);
int ldow = localizedDayOfWeek(date);
int offset = startOfWeekOffset(1, ldow);
// Clamp the week of year to keep it in the same year
int yearLen = date.lengthOfYear();
int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());
wowby = Math.min(wowby, newYearWeek - 1);
int days = -offset + (dow - 1) + (wowby - 1) * 7;
return date.plus(days, DAYS);
}
private void updateCheckConflict(ChronoLocalDate cld) {
if (date != null) {
if (cld != null && date.equals(cld) == false) {
throw new DateTimeException("Conflict found: Fields resolved to two different dates: " + date + " " + cld);
}
} else if (cld != null) {
if (chrono.equals(cld.getChronology()) == false) {
throw new DateTimeException("ChronoLocalDate must use the effective parsed chronology: " + chrono);
}
date = cld;
}
}
@Override
public ChronoLocalDate resolve(
Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {
long value = fieldValues.remove(this);
Chronology chrono = Chronology.from(partialTemporal);
if (resolverStyle == ResolverStyle.LENIENT) {
return chrono.dateEpochDay(Math.subtractExact(value, offset));
}
range().checkValidValue(value, this);
return chrono.dateEpochDay(value - offset);
}
@Test
public void test_TestServiceLoader() {
Chronology chrono = Chronology.of("Coptic");
ChronoLocalDate copticDate = chrono.date(1729, 4, 27);
LocalDate ld = LocalDate.from(copticDate);
assertEquals(ld, LocalDate.of(2013, 1, 5), "CopticDate does not match LocalDate");
}