@Test(dataProvider="calendars") public void test_badWithAdjusterChrono(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); TemporalAdjuster adjuster = new FixedAdjuster(date2); if (chrono != chrono2) { try { date.with(adjuster); Assert.fail("WithAdjuster should have thrown a ClassCastException"); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDate result = date.with(adjuster); assertEquals(result, date2, "WithAdjuster failed to replace date"); } } }
/** * 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="calendars") public void test_badPlusAdjusterChrono(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.plus(adjuster); Assert.fail("WithAdjuster should have thrown a ClassCastException"); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDate result = date.plus(adjuster); assertEquals(result, date2, "WithAdjuster failed to replace date"); } } }
@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"); } } }
/** * 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; }
/** * Ensures that the date pickers only allow selection of dates within the valid booking date * range, as defined in the specifications document. * * Chief among these rules is that bookings may not be placed more than one year in advance. */ private void initializeDatePickers() { Callback<DatePicker, DateCell> dayCellFactory = (final DatePicker datePicker) -> new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); if(item.isAfter(LocalDate.now().plusYears(1))) { setDisable(true); } if(item.isBefore(ChronoLocalDate.from(LocalDate.now()))) { setDisable(true); } } }; // Disable selecting invalid check-in/check-out dates checkInDatePicker.setDayCellFactory(dayCellFactory); checkOutDatePicker.setDayCellFactory(dayCellFactory); }
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); }
@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_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)); }
public void test_date_comparator_checkGenerics_ISO() { List<ChronoLocalDate> dates = new ArrayList<>(); ChronoLocalDate 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<ChronoLocalDate> 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); }
@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); }
@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); }
/** * 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(dataProvider = "epochSecond_dataProvider") public void test_epochSecond(Chronology chrono, int y, int m, int d, int h, int min, int s, ZoneOffset offset) { ChronoLocalDate chronoLd = chrono.date(y, m, d); assertEquals(chrono.epochSecond(y, m, d, h, min, s, offset), OffsetDateTime.of(LocalDate.from(chronoLd), LocalTime.of(h, min, s), offset) .toEpochSecond()); }
@Test public void test_MinguoChronology_dateYearDay() { Chronology chrono = Chronology.of("Minguo"); ChronoLocalDate date1 = chrono.dateYearDay(MinguoEra.ROC, 5, 60); ChronoLocalDate date2 = chrono.date(MinguoEra.ROC, 5, 2, 29); assertEquals(date1, MinguoChronology.INSTANCE.dateYearDay(MinguoEra.ROC, 5, 60)); assertEquals(date2, MinguoChronology.INSTANCE.dateYearDay(MinguoEra.ROC, 5, 60)); }
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_calendarPackageExample() { // 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 the Thai Buddhist date ThaiBuddhistDate now1 = ThaiBuddhistDate.now(); 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); // Print today's date and the last day of the year for the Thai Buddhist Calendar. ThaiBuddhistDate first = now1 .with(ChronoField.DAY_OF_MONTH, 1) .with(ChronoField.MONTH_OF_YEAR, 1); ThaiBuddhistDate 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); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ChronoLocalDate) { return compareTo((ChronoLocalDate<?>) obj) == 0; } return false; }
/** * Try to obtain the {@link TemporalType} of given <code>expression</code>, if the expression type is a temporal * type. * @param expression Query expression * @param treatDateTypeAsDate <code>true</code> to return {@link TemporalType#DATE} for {@link Date} type if * temporal information is not available * @return The expression {@link TemporalType}, empty if not available or applicable */ public static Optional<TemporalType> getTemporalType(Expression expression, boolean treatDateTypeAsDate) { if (expression != null) { Class<?> type = null; if (Path.class.isAssignableFrom(expression.getClass())) { type = ((Path<?>) expression).getType(); } else if (QueryExpression.class.isAssignableFrom(expression.getClass())) { type = ((QueryExpression<?>) expression).getType(); } if (type != null) { if (LocalDate.class.isAssignableFrom(type) || ChronoLocalDate.class.isAssignableFrom(type)) { return Optional.of(TemporalType.DATE); } if (LocalTime.class.isAssignableFrom(type) || OffsetTime.class.isAssignableFrom(type)) { return Optional.of(TemporalType.TIME); } if (LocalDateTime.class.isAssignableFrom(type) || OffsetDateTime.class.isAssignableFrom(type) || ZonedDateTime.class.isAssignableFrom(type) || ChronoLocalDateTime.class.isAssignableFrom(type)) { return Optional.of(TemporalType.DATE); } if (Date.class.isAssignableFrom(type) || Calendar.class.isAssignableFrom(type)) { if (Property.class.isAssignableFrom(expression.getClass())) { Optional<TemporalType> tt = ((Property<?>) expression).getConfiguration().getTemporalType(); return treatDateTypeAsDate ? Optional.of(tt.orElse(TemporalType.DATE)) : tt; } else { return treatDateTypeAsDate ? Optional.of(TemporalType.DATE) : Optional.empty(); } } } } return Optional.empty(); }
private boolean checkChronoLocalDate(final Class<?> type) { if (!ChronoLocalDate.class.isAssignableFrom(type)) { return false; } try { Method method = type.getMethod("of", int.class, int.class, int.class); return Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers()) && method.getReturnType().equals(type); } catch (NoSuchMethodException | SecurityException e) { return false; } }
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; } }
@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 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"); }
/** * 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(dataProvider = "calendarNameAndType") public void test_dateEpochDay(String name, String alias) { Chronology chrono = Chronology.of(name); ChronoLocalDate date = chrono.dateNow(); long epochDay = date.getLong(ChronoField.EPOCH_DAY); ChronoLocalDate test = chrono.dateEpochDay(epochDay); assertEquals(test, date); }
@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_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 public void test_JapaneseChronology_dateYearDay() { Chronology chrono = Chronology.of("Japanese"); ChronoLocalDate date1 = chrono.dateYearDay(JapaneseEra.HEISEI, 8, 60); ChronoLocalDate date2 = chrono.date(JapaneseEra.HEISEI, 8, 2, 29); assertEquals(date1, JapaneseChronology.INSTANCE.dateYearDay(JapaneseEra.HEISEI, 8, 60)); assertEquals(date2, JapaneseChronology.INSTANCE.dateYearDay(JapaneseEra.HEISEI, 8, 60)); }