@Test(dataProvider="calendars") public void test_badMinusAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime<?> cdt = chrono.date(refDate).atTime(LocalTime.NOON); for (Chronology[] clist : data_of_calendars()) { Chronology chrono2 = clist[0]; ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON); TemporalAmount adjuster = new FixedAdjuster(cdt2); if (chrono != chrono2) { try { cdt.minus(adjuster); Assert.fail("WithAdjuster should have thrown a ClassCastException, " + "required: " + cdt + ", supplied: " + cdt2); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDateTime<?> result = cdt.minus(adjuster); assertEquals(result, cdt2, "WithAdjuster failed to replace date"); } } }
@Test(dataProvider="calendars") public void test_badPlusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); for (Chronology[] clist : data_of_calendars()) { Chronology chrono2 = clist[0]; ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); TemporalUnit adjuster = new FixedTemporalUnit(czdt2); if (chrono != chrono2) { try { czdt.plus(1, adjuster); Assert.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException, " + czdt + " can not be cast to " + czdt2); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoZonedDateTime<?> result = czdt.plus(1, adjuster); assertEquals(result, czdt2, "WithAdjuster failed to replace date"); } } }
/** * Gets the text for the specified chrono, field, locale and style * for the purpose of formatting. * <p> * The text associated with the value is returned. * The null return value should be used if there is no applicable text, or * if the text would be a numeric representation of the value. * * @param chrono the Chronology to get text for, not null * @param field the field to get text for, not null * @param value the field value to get text for, not null * @param style the style to get text for, not null * @param locale the locale to get text for, not null * @return the text for the field value, null if no text found */ public String getText(Chronology chrono, TemporalField field, long value, TextStyle style, Locale locale) { if (chrono == IsoChronology.INSTANCE || !(field instanceof ChronoField)) { return getText(field, value, style, locale); } int fieldIndex; int fieldValue; if (field == ERA) { fieldIndex = Calendar.ERA; if (chrono == JapaneseChronology.INSTANCE) { if (value == -999) { fieldValue = 0; } else { fieldValue = (int) value + 2; } } else { fieldValue = (int) value; } } else if (field == MONTH_OF_YEAR) { fieldIndex = Calendar.MONTH; fieldValue = (int) value - 1; } else if (field == DAY_OF_WEEK) { fieldIndex = Calendar.DAY_OF_WEEK; fieldValue = (int) value + 1; if (fieldValue > 7) { fieldValue = Calendar.SUNDAY; } } else if (field == AMPM_OF_DAY) { fieldIndex = Calendar.AM_PM; fieldValue = (int) value; } else { return null; } return CalendarDataUtility.retrieveJavaTimeFieldValueName( chrono.getCalendarType(), fieldIndex, fieldValue, style.toCalendarStyle(), locale); }
@Override public boolean format(DateTimePrintContext context, StringBuilder buf) { Long value = context.getValue(field); if (value == null) { return false; } String text; Chronology chrono = context.getTemporal().query(TemporalQueries.chronology()); if (chrono == null || chrono == IsoChronology.INSTANCE) { text = provider.getText(field, value, textStyle, context.getLocale()); } else { text = provider.getText(chrono, field, value, textStyle, context.getLocale()); } if (text == null) { return numberPrinterParser().format(context, buf); } buf.append(text); return true; }
@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"); } } }
@Test public void test_throws_message_chrono() { Chronology chrono = ThaiBuddhistChronology.INSTANCE; DateTimeFormatter fmt = new DateTimeFormatterBuilder().appendZoneId().toFormatter() .withChronology(chrono); LocalTime now = LocalTime.now(); try { fmt.format(now); fail("Format using appendZoneId() should have failed"); } catch (DateTimeException dte) { String msg = dte.getMessage(); // Verify message contains the type that is missing and the temporal value assertTrue(msg.contains("ZoneId"), String.format("\"%s\" missing from %s", "ZoneId", msg)); assertTrue(msg.contains(chrono.toString()), String.format("\"%s\" missing from %s", chrono.toString(), msg)); } }
@Test(dataProvider="calendars") public void test_badPlusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime<?> cdt = chrono.date(refDate).atTime(LocalTime.NOON); for (Chronology[] clist : data_of_calendars()) { Chronology chrono2 = clist[0]; ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON); TemporalUnit adjuster = new FixedTemporalUnit(cdt2); if (chrono != chrono2) { try { cdt.plus(1, adjuster); Assert.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException" + cdt + ", can not be cast to " + cdt2); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDateTime<?> result = cdt.plus(1, adjuster); assertEquals(result, cdt2, "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"); } } }
@Test(dataProvider="calendars") public void test_badMinusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime<?> cdt = chrono.date(refDate).atTime(LocalTime.NOON); for (Chronology[] clist : data_of_calendars()) { Chronology chrono2 = clist[0]; ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON); TemporalUnit adjuster = new FixedTemporalUnit(cdt2); if (chrono != chrono2) { try { cdt.minus(1, adjuster); Assert.fail("TemporalUnit.doPlus minus should have thrown a ClassCastException" + cdt.getClass() + ", can not be cast to " + cdt2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDateTime<?> result = cdt.minus(1, adjuster); assertEquals(result, cdt2, "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)); }
@Test(dataProvider="formatWithZoneWithChronology") public void test_format_withZone_withChronology(Chronology overrideChrono, ZoneId overrideZone, TemporalAccessor temporal, String expected) { DateTimeFormatter test = new DateTimeFormatterBuilder() .optionalStart().appendValue(YEAR, 4).optionalEnd() .appendLiteral(':').optionalStart().appendValue(HOUR_OF_DAY, 2).optionalEnd() .appendLiteral(':').optionalStart().appendOffsetId().optionalEnd() .appendLiteral(':').optionalStart().appendZoneId().optionalEnd() .appendLiteral(':').optionalStart().appendChronologyId().optionalEnd() .toFormatter(Locale.ENGLISH) .withChronology(overrideChrono).withZone(overrideZone); if (expected != null) { String result = test.format(temporal); assertEquals(result, expected); } else { try { test.format(temporal); fail("Formatting should have failed"); } catch (DateTimeException ex) { // expected } } }
@DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, {IsoChronology.INSTANCE}, {JapaneseChronology.INSTANCE}, {MinguoChronology.INSTANCE}, {ThaiBuddhistChronology.INSTANCE}}; }
/** * Test lookup by calendarType of each chronology. * Verify that the calendar can be found by {@link java.time.chrono.Chronology#ofLocale}. */ @Test public void test_ofLocaleByType() { // Test that all available chronologies can be successfully found using ofLocale Set<Chronology> chronos = Chronology.getAvailableChronologies(); for (Chronology chrono : chronos) { Locale.Builder builder = new Locale.Builder().setLanguage("en").setRegion("CA"); builder.setUnicodeLocaleKeyword("ca", chrono.getCalendarType()); Locale locale = builder.build(); assertEquals(Chronology.ofLocale(locale), chrono, "Lookup by type"); } }
@Test(dataProvider="chrono_names") public void test_chronoNames(Chronology chrono, Locale locale, String expected) { DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendChronologyText(TextStyle.SHORT) .toFormatter(locale); String text = dtf.format(chrono.dateNow()); assertEquals(text, expected); TemporalAccessor ta = dtf.parse(text); Chronology cal = ta.query(TemporalQueries.chronology()); assertEquals(cal, chrono); }
/** * 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); }
/** * Constructor. * * @param printerParser the printer/parser to use, not null * @param locale the locale to use, not null * @param decimalStyle the DecimalStyle to use, not null * @param resolverStyle the resolver style to use, not null * @param resolverFields the fields to use during resolving, null for all fields * @param chrono the chronology to use, null for no override * @param zone the zone to use, null for no override */ DateTimeFormatter(CompositePrinterParser printerParser, Locale locale, DecimalStyle decimalStyle, ResolverStyle resolverStyle, Set<TemporalField> resolverFields, Chronology chrono, ZoneId zone) { this.printerParser = Objects.requireNonNull(printerParser, "printerParser"); this.resolverFields = resolverFields; this.locale = Objects.requireNonNull(locale, "locale"); this.decimalStyle = Objects.requireNonNull(decimalStyle, "decimalStyle"); this.resolverStyle = Objects.requireNonNull(resolverStyle, "resolverStyle"); this.chrono = chrono; this.zone = zone; }
@Test public void test_ThaiBuddhistChronology_dateYearDay() { Chronology chrono = Chronology.of("ThaiBuddhist"); ChronoLocalDate date1 = chrono.dateYearDay(ThaiBuddhistEra.BE, 2459, 60); ChronoLocalDate date2 = chrono.date(ThaiBuddhistEra.BE, 2459, 2, 29); assertEquals(date1, ThaiBuddhistChronology.INSTANCE.dateYearDay(ThaiBuddhistEra.BE, 2459, 60)); assertEquals(date2, ThaiBuddhistChronology.INSTANCE.dateYearDay(ThaiBuddhistEra.BE, 2459, 60)); }
@Test(dataProvider="calendars") public void test_from_TemporalAccessor(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); ChronoLocalDate test1 = ChronoLocalDate.from(date); assertEquals(test1, date); ChronoLocalDate test2 = ChronoLocalDate.from(date.atTime(LocalTime.of(12, 30))); assertEquals(test2, date); ChronoLocalDate test3 = ChronoLocalDate.from(date.atTime(LocalTime.of(12, 30)).atZone(ZoneOffset.UTC)); assertEquals(test3, date); }
/** * Adds a Consumer<Chronology> to the list of listeners to be notified * if the Chronology changes. * @param listener a Consumer<Chronology> to be called when Chronology changes */ void addChronoChangedListener(Consumer<Chronology> listener) { if (chronoListeners == null) { chronoListeners = new ArrayList<Consumer<Chronology>>(); } chronoListeners.add(listener); }
@Test(dataProvider="calendars") public void test_serialization(Chronology chrono) throws Exception { ChronoPeriod period = chrono.period(1, 2, 3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(period); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); ChronoPeriod ser = (ChronoPeriod) in.readObject(); assertEquals(ser, period, "deserialized ChronoPeriod is wrong"); }
@Override long getValue(DateTimePrintContext context, long value) { long absValue = Math.abs(value); int baseValue = this.baseValue; if (baseDate != null) { Chronology chrono = Chronology.from(context.getTemporal()); baseValue = chrono.date(baseDate).get(field); } if (value >= baseValue && value < baseValue + EXCEED_POINTS[minWidth]) { // Use the reduced value if it fits in minWidth return absValue % EXCEED_POINTS[minWidth]; } // Otherwise truncate to fit in maxWidth return absValue % EXCEED_POINTS[maxWidth]; }
@Test(dataProvider="calendars") public void test_isZero_isNegative(Chronology chrono) { ChronoPeriod periodPositive = chrono.period(1, 2, 3); assertEquals(periodPositive.isZero(), false); assertEquals(periodPositive.isNegative(), false); ChronoPeriod periodZero = chrono.period(0, 0, 0); assertEquals(periodZero.isZero(), true); assertEquals(periodZero.isNegative(), false); ChronoPeriod periodNegative = chrono.period(-1, 0, 0); assertEquals(periodNegative.isZero(), false); assertEquals(periodNegative.isNegative(), true); }
@Test(dataProvider="format_data") public void test_formatLocalizedDate(Chronology chrono, Locale formatLocale, Locale numberingLocale, ChronoLocalDate date, String expected) { DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) .withChronology(chrono).withLocale(formatLocale) .withDecimalStyle(DecimalStyle.of(numberingLocale)); String text = dtf.format(date); assertEquals(text, expected); }
@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(dataProvider = "calendarsystemtype") public void test_lookupLocale(Chronology chrono, String calendarType) { Locale.Builder builder = new Locale.Builder().setLanguage("en").setRegion("CA"); builder.setUnicodeLocaleKeyword("ca", calendarType); Locale locale = builder.build(); assertEquals(Chronology.ofLocale(locale), chrono); }
@Test public void test_ThaiBuddhistChronology_dateNow() { ZoneId zoneId_paris = ZoneId.of("Europe/Paris"); Clock clock = Clock.system(zoneId_paris); Chronology chrono = Chronology.of("ThaiBuddhist"); assertEquals(chrono.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow()); assertEquals(chrono.dateNow(zoneId_paris), ThaiBuddhistChronology.INSTANCE.dateNow(zoneId_paris)); assertEquals(chrono.dateNow(clock), ThaiBuddhistChronology.INSTANCE.dateNow(clock)); }
/** * Validates that the temporal has the correct chronology. */ private void validateChrono(TemporalAccessor temporal) { Objects.requireNonNull(temporal, "temporal"); Chronology temporalChrono = temporal.query(TemporalQueries.chronology()); if (temporalChrono != null && IsoChronology.INSTANCE.equals(temporalChrono) == false) { throw new DateTimeException("Chronology mismatch, expected: ISO, actual: " + temporalChrono.getId()); } }
/** * Completes this builder by creating the formatter. * * @param locale the locale to use for formatting, not null * @param chrono the chronology to use, may be null * @return the created formatter, not null */ private DateTimeFormatter toFormatter(Locale locale, ResolverStyle resolverStyle, Chronology chrono) { Objects.requireNonNull(locale, "locale"); while (active.parent != null) { optionalEnd(); } CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false); return new DateTimeFormatter(pp, locale, DecimalStyle.STANDARD, resolverStyle, null, chrono, null); }
@Test(dataProvider="calendars") public void test_toString(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); if (period instanceof Period == false) { assertEquals(period.toString(), chrono.getId() + " P1Y2M3D"); } }
@Test public void test_chrono_byName() { Chronology c = ThaiBuddhistChronology.INSTANCE; Chronology test = Chronology.of("ThaiBuddhist"); Assert.assertNotNull(test, "The ThaiBuddhist calendar could not be found byName"); Assert.assertEquals(test.getId(), "ThaiBuddhist", "ID mismatch"); Assert.assertEquals(test.getCalendarType(), "buddhist", "Type mismatch"); Assert.assertEquals(test, c); }
@Test(dataProvider="calendars") public void test_getUnits(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); assertEquals(period.getUnits().size(), 3); assertEquals(period.getUnits().get(0), YEARS); assertEquals(period.getUnits().get(1), MONTHS); assertEquals(period.getUnits().get(2), DAYS); }
@Override public int parse(DateTimeParseContext context, CharSequence parseText, int position) { int length = parseText.length(); if (position < 0 || position > length) { throw new IndexOutOfBoundsException(); } TextStyle style = (context.isStrict() ? textStyle : null); Chronology chrono = context.getEffectiveChronology(); Iterator<Entry<String, Long>> it; if (chrono == null || chrono == IsoChronology.INSTANCE) { it = provider.getTextIterator(field, style, context.getLocale()); } else { it = provider.getTextIterator(chrono, field, style, context.getLocale()); } if (it != null) { while (it.hasNext()) { Entry<String, Long> entry = it.next(); String itText = entry.getKey(); if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) { return context.setParsedField(field, entry.getValue(), position, position + itText.length()); } } if (field == ERA && !context.isStrict()) { // parse the possible era name from era.toString() List<Era> eras = chrono.eras(); for (Era era : eras) { String name = era.toString(); if (context.subSequenceEquals(name, 0, parseText, position, name.length())) { return context.setParsedField(field, era.getValue(), position, position + name.length()); } } } if (context.isStrict()) { return ~position; } } return numberPrinterParser().parse(context, parseText, position); }
@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"); }