java.time.temporal.TemporalAccessor Java Examples
The following examples show how to use
java.time.temporal.TemporalAccessor.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TCKDateTimeParseResolver.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@Test public void test_parse_fromField_InstantSeconds() { DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendValue(INSTANT_SECONDS).toFormatter(); TemporalAccessor acc = fmt.parse("86402"); Instant expected = Instant.ofEpochSecond(86402); assertEquals(acc.isSupported(INSTANT_SECONDS), true); assertEquals(acc.isSupported(NANO_OF_SECOND), true); assertEquals(acc.isSupported(MICRO_OF_SECOND), true); assertEquals(acc.isSupported(MILLI_OF_SECOND), true); assertEquals(acc.getLong(INSTANT_SECONDS), 86402L); assertEquals(acc.getLong(NANO_OF_SECOND), 0L); assertEquals(acc.getLong(MICRO_OF_SECOND), 0L); assertEquals(acc.getLong(MILLI_OF_SECOND), 0L); assertEquals(Instant.from(acc), expected); }
Example #2
Source File: DateTimeFormatter.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Formats a date-time object to an {@code Appendable} using this formatter. * <p> * This outputs the formatted date-time to the specified destination. * {@link Appendable} is a general purpose interface that is implemented by all * key character output classes including {@code StringBuffer}, {@code StringBuilder}, * {@code PrintStream} and {@code Writer}. * <p> * Although {@code Appendable} methods throw an {@code IOException}, this method does not. * Instead, any {@code IOException} is wrapped in a runtime exception. * * @param temporal the temporal object to format, not null * @param appendable the appendable to format to, not null * @throws DateTimeException if an error occurs during formatting */ public void formatTo(TemporalAccessor temporal, Appendable appendable) { Objects.requireNonNull(temporal, "temporal"); Objects.requireNonNull(appendable, "appendable"); try { DateTimePrintContext context = new DateTimePrintContext(temporal, this); if (appendable instanceof StringBuilder) { printerParser.format(context, (StringBuilder) appendable); } else { // buffer output to avoid writing to appendable in case of error StringBuilder buf = new StringBuilder(32); printerParser.format(context, buf); appendable.append(buf); } } catch (IOException ex) { throw new DateTimeException(ex.getMessage(), ex); } }
Example #3
Source File: TCKLocalizedFieldParser.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
@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); } }
Example #4
Source File: AbstractDateTimeTest.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
@Test() public void basicTest_get_TemporalField_supported() { for (TemporalAccessor sample : samples()) { for (TemporalField field : validFields()) { if (sample.range(field).isIntValue()) { sample.get(field); // no exception } else { try { sample.get(field); fail("Failed on " + sample + " " + field); } catch (DateTimeException ex) { // expected } } } } }
Example #5
Source File: DateTimeFormatterBuilder.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
@Override public boolean format(DateTimePrintContext context, StringBuilder buf) { ZoneId zone = context.getValue(TemporalQueries.zoneId()); if (zone == null) { return false; } String zname = zone.getId(); if (!(zone instanceof ZoneOffset)) { TemporalAccessor dt = context.getTemporal(); String name = getDisplayName(zname, dt.isSupported(ChronoField.INSTANT_SECONDS) ? (zone.getRules().isDaylightSavings(Instant.from(dt)) ? DST : STD) : GENERIC, context.getLocale()); if (name != null) { zname = name; } } buf.append(zname); return true; }
Example #6
Source File: TCKDateTimeParseResolver.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
@Test(dataProvider="resolveTwoToField") public void test_resolveTwoToField(TemporalField field1, long value1, TemporalField field2, long value2, TemporalField expectedField1, Long expectedValue1, TemporalField expectedField2, Long expectedValue2) { String str = value1 + " " + value2; DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(field1).appendLiteral(' ') .appendValue(field2).toFormatter(); TemporalAccessor accessor = f.parse(str); assertEquals(accessor.query(TemporalQueries.localDate()), null); assertEquals(accessor.query(TemporalQueries.localTime()), null); if (expectedField1 != null) { assertEquals(accessor.isSupported(expectedField1), true); assertEquals(accessor.getLong(expectedField1), expectedValue1.longValue()); } if (expectedField2 != null) { assertEquals(accessor.isSupported(expectedField2), true); assertEquals(accessor.getLong(expectedField2), expectedValue2.longValue()); } }
Example #7
Source File: TCKDateTimeFormatters.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
@Test(dataProvider="sample_isoLocalDate") public void test_print_isoLocalDate( Integer year, Integer month, Integer day, String offsetId, String zoneId, String expected, Class<?> expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatter.ISO_LOCAL_DATE.format(test), expected); } else { try { DateTimeFormatter.ISO_LOCAL_DATE.format(test); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
Example #8
Source File: Parsed.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
private void crossCheck(TemporalAccessor target) { for (Iterator<Entry<TemporalField, Long>> it = fieldValues.entrySet().iterator(); it.hasNext(); ) { Entry<TemporalField, Long> entry = it.next(); TemporalField field = entry.getKey(); if (target.isSupported(field)) { long val1; try { val1 = target.getLong(field); } catch (RuntimeException ex) { continue; } long val2 = entry.getValue(); if (val1 != val2) { throw new DateTimeException("Conflict found: Field " + field + " " + val1 + " differs from " + field + " " + val2 + " derived from " + target); } it.remove(); } } }
Example #9
Source File: TestReducedParser.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
@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)); }
Example #10
Source File: DateTimeFormatter.java From JDKSourceCode1.8 with MIT License | 6 votes |
/** * Parses and resolves the specified text. * <p> * This parses to a {@code TemporalAccessor} ensuring that the text is fully parsed. * * @param text the text to parse, not null * @param position the position to parse from, updated with length parsed * and the index of any error, null if parsing whole string * @return the resolved result of the parse, not null * @throws DateTimeParseException if the parse fails * @throws DateTimeException if an error occurs while resolving the date or time * @throws IndexOutOfBoundsException if the position is invalid */ private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) { ParsePosition pos = (position != null ? position : new ParsePosition(0)); DateTimeParseContext context = parseUnresolved0(text, pos); if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) { String abbr; if (text.length() > 64) { abbr = text.subSequence(0, 64).toString() + "..."; } else { abbr = text.toString(); } if (pos.getErrorIndex() >= 0) { throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " + pos.getErrorIndex(), text, pos.getErrorIndex()); } else { throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " + pos.getIndex(), text, pos.getIndex()); } } return context.toResolved(resolverStyle, resolverFields); }
Example #11
Source File: AbstractDateTimeTest.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
@Test() public void basicTest_range_TemporalField_supported() { for (TemporalAccessor sample : samples()) { for (TemporalField field : validFields()) { sample.range(field); // no exception } } }
Example #12
Source File: TestNumberParser.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider="parseDigitsLenient") public void test_parseDigitsLenient(String input, int min, int max, SignStyle style, int parseLen, Integer parseVal) throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(DAY_OF_MONTH, min, max, style).parseUnresolved(input, pos); if (pos.getErrorIndex() != -1) { assertEquals(pos.getErrorIndex(), parseLen); } else { assertEquals(pos.getIndex(), parseLen); assertEquals(parsed.getLong(DAY_OF_MONTH), (long)parseVal); assertEquals(parsed.query(TemporalQueries.chronology()), null); assertEquals(parsed.query(TemporalQueries.zoneId()), null); } }
Example #13
Source File: TCKChronoPrinterParser.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider="parseInvalid") public void test_parseInvalid(String text) { builder.appendChronologyId(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos); assertEquals(pos.getIndex(), 0); assertEquals(pos.getErrorIndex(), 0); assertEquals(parsed, null); }
Example #14
Source File: TCKDateTimeFormatters.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private TemporalAccessor buildAccessor( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId) { MockAccessor mock = new MockAccessor(); if (year != null) { mock.fields.put(YEAR, (long) year); } if (month != null) { mock.fields.put(MONTH_OF_YEAR, (long) month); } if (day != null) { mock.fields.put(DAY_OF_MONTH, (long) day); } if (hour != null) { mock.fields.put(HOUR_OF_DAY, (long) hour); } if (min != null) { mock.fields.put(MINUTE_OF_HOUR, (long) min); } if (sec != null) { mock.fields.put(SECOND_OF_MINUTE, (long) sec); } if (nano != null) { mock.fields.put(NANO_OF_SECOND, (long) nano); } mock.setOffset(offsetId); mock.setZone(zoneId); return mock; }
Example #15
Source File: TestZoneOffsetParser.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider="offsets") public void test_parse_endStringMatch_EmptyUTC(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved("OTHER" + parse, pos); assertEquals(pos.getIndex(), parse.length() + 5); assertParsed(parsed, expected); }
Example #16
Source File: TomlWriter.java From LightningStorage with Apache License 2.0 | 5 votes |
private void writeValue(final Object value) throws IOException { if (value instanceof String) { writeString((String) value); } else if (value instanceof Number || value instanceof Boolean) { write(value.toString()); } else if (value instanceof TemporalAccessor) { String formatted = TomlManager.DATE_FORMATTER.format((TemporalAccessor) value); if (formatted.endsWith("T")) // If the last character is a 'T' { formatted = formatted.substring(0, formatted.length() - 1); // removes it because it's invalid. } write(formatted); } else if (value instanceof Collection) { writeArray((Collection) value); } else if (value instanceof int[]) { writeArray((int[]) value); } else if (value instanceof byte[]) { writeArray((byte[]) value); } else if (value instanceof short[]) { writeArray((short[]) value); } else if (value instanceof char[]) { writeArray((char[]) value); } else if (value instanceof long[]) { writeArray((long[]) value); } else if (value instanceof float[]) { writeArray((float[]) value); } else if (value instanceof double[]) { writeArray((double[]) value); } else if (value instanceof Map) { // should not happen because an array of tables is detected by // writeTableContent() throw new IOException("Unexpected value " + value); } else { throw new TomlException("Unsupported value of type " + value.getClass().getCanonicalName()); } }
Example #17
Source File: TCKZoneIdPrinterParser.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider="parseSuccess") public void test_parseSuccess_plain(String text, int expectedIndex, int expectedErrorIndex, ZoneId expected) { builder.appendZoneId(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos); assertEquals(pos.getErrorIndex(), expectedErrorIndex, "Incorrect error index parsing: " + text); assertEquals(pos.getIndex(), expectedIndex, "Incorrect index parsing: " + text); if (expected != null) { assertEquals(parsed.query(TemporalQueries.zoneId()), expected, "Incorrect zoneId parsing: " + text); assertEquals(parsed.query(TemporalQueries.offset()), null, "Incorrect offset parsing: " + text); assertEquals(parsed.query(TemporalQueries.zone()), expected, "Incorrect zone parsing: " + text); } else { assertEquals(parsed, null); } }
Example #18
Source File: TCKDateTimeParseResolver.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
@Test public void test_fieldResolvesToChronoZonedDateTime_overrideChrono_matches() { MinguoDate mdt = MinguoDate.of(100, 6, 30); ChronoZonedDateTime<MinguoDate> mzdt = mdt.atTime(LocalTime.NOON).atZone(EUROPE_PARIS); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(mzdt)).toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse("1234567890"); assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.from(mdt)); assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.NOON); assertEquals(accessor.query(TemporalQueries.chronology()), MinguoChronology.INSTANCE); assertEquals(accessor.query(TemporalQueries.zoneId()), EUROPE_PARIS); }
Example #19
Source File: TCKDateTimeParseResolver.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
@Test public void test_fieldResolvesToChronoLocalDate_overrideChrono_matches() { MinguoDate mdt = MinguoDate.of(100, 6, 30); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(mdt)).toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse("1234567890"); assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.from(mdt)); assertEquals(accessor.query(TemporalQueries.localTime()), null); assertEquals(accessor.query(TemporalQueries.chronology()), MinguoChronology.INSTANCE); }
Example #20
Source File: TCKDateTimeParseResolver.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
@Test public void test_fieldResolvesToChronoZonedDateTime_noOverrideChrono_matches() { ZonedDateTime zdt = ZonedDateTime.of(2010, 6, 30, 12, 30, 0, 0, EUROPE_PARIS); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(zdt)).toFormatter(); TemporalAccessor accessor = f.parse("1234567890"); assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(2010, 6, 30)); assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(12, 30)); assertEquals(accessor.query(TemporalQueries.chronology()), IsoChronology.INSTANCE); assertEquals(accessor.query(TemporalQueries.zoneId()), EUROPE_PARIS); }
Example #21
Source File: TCKDateTimeFormatterBuilder.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Test public void test_adjacent_strict_firstVariableWidth_fails() throws Exception { // fails because literal is a number and variable width parse greedily absorbs it DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('9').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309", pp); assertEquals(pp.getErrorIndex(), 5); assertEquals(parsed, null); }
Example #22
Source File: TestDateTimeFormatterBuilder.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Test public void test_appendValue_subsequent2_parse5() throws Exception { builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValue(DAY_OF_MONTH, 2).appendLiteral('4'); DateTimeFormatter f = builder.toFormatter(); assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)'4'"); TemporalAccessor parsed = f.parseUnresolved("01234", new ParsePosition(0)); assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L); assertEquals(parsed.getLong(DAY_OF_MONTH), 23L); }
Example #23
Source File: TestDateTimeParsing.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider = "instantNoZone") public void test_parse_instantNoZone_supported(DateTimeFormatter formatter, String text, Instant expected) { TemporalAccessor actual = formatter.parse(text); assertEquals(actual.isSupported(INSTANT_SECONDS), true); assertEquals(actual.isSupported(EPOCH_DAY), false); assertEquals(actual.isSupported(SECOND_OF_DAY), false); assertEquals(actual.isSupported(NANO_OF_SECOND), true); assertEquals(actual.isSupported(MICRO_OF_SECOND), true); assertEquals(actual.isSupported(MILLI_OF_SECOND), true); }
Example #24
Source File: TCKDateTimeParseResolver.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
@Test public void test_withChronology_parsedChronology_override() { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).appendChronologyId().toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse("ThaiBuddhist"); assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); assertEquals(accessor.query(TemporalQueries.localTime()), null); assertEquals(accessor.query(TemporalQueries.chronology()), ThaiBuddhistChronology.INSTANCE); }
Example #25
Source File: AbstractDateTimeTest.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
@Test() public void basicTest_getLong_TemporalField_null() { for (TemporalAccessor sample : samples()) { try { sample.getLong(null); fail("Failed on " + sample); } catch (NullPointerException ex) { // expected } } }
Example #26
Source File: TestTextParser.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public void test_parse_noMatch1() throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(DAY_OF_WEEK, TextStyle.FULL).parseUnresolved("Munday", pos); assertEquals(pos.getErrorIndex(), 0); assertEquals(parsed, null); }
Example #27
Source File: TestZoneOffsetParser.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public void test_parse_caseInsensitiveUTC_matchedCase() throws Exception { setCaseSensitive(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("Z", pos); assertEquals(pos.getIndex(), 1); assertParsed(parsed, ZoneOffset.UTC); }
Example #28
Source File: TestZoneOffsetParser.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider="offsets") public void test_parse_exactMatch_EmptyUTC(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved(parse, pos); assertEquals(pos.getIndex(), parse.length()); assertParsed(parsed, expected); }
Example #29
Source File: TCKDateTimeParseResolver.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Test public void test_parse_fromField_SecondOfMinute_NanoOfSecond() { DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendValue(SECOND_OF_MINUTE).appendLiteral('.').appendValue(NANO_OF_SECOND).toFormatter(); TemporalAccessor acc = fmt.parse("32.123456789"); assertEquals(acc.isSupported(SECOND_OF_MINUTE), true); assertEquals(acc.isSupported(NANO_OF_SECOND), true); assertEquals(acc.isSupported(MICRO_OF_SECOND), true); assertEquals(acc.isSupported(MILLI_OF_SECOND), true); assertEquals(acc.getLong(SECOND_OF_MINUTE), 32L); assertEquals(acc.getLong(NANO_OF_SECOND), 123456789L); assertEquals(acc.getLong(MICRO_OF_SECOND), 123456L); assertEquals(acc.getLong(MILLI_OF_SECOND), 123L); }
Example #30
Source File: TestNumberParser.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider="parseSignsLenient") public void test_parseSignsLenient(String input, int min, int max, SignStyle style, int parseLen, Integer parseVal) throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(DAY_OF_MONTH, min, max, style).parseUnresolved(input, pos); if (pos.getErrorIndex() != -1) { assertEquals(pos.getErrorIndex(), parseLen); } else { assertEquals(pos.getIndex(), parseLen); assertEquals(parsed.getLong(DAY_OF_MONTH), (long)parseVal); assertEquals(parsed.query(TemporalQueries.chronology()), null); assertEquals(parsed.query(TemporalQueries.zoneId()), null); } }