Java Code Examples for java.time.format.DateTimeFormatter#parse()

The following examples show how to use java.time.format.DateTimeFormatter#parse() . 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: TestDateTimeFormatterBuilderWithLocale.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: TCKDateTimeParseResolver.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="resolveTwoToTime")
public void test_resolveTwoToTime(TemporalField field1, long value1,
                            TemporalField field2, long value2,
                            LocalTime expectedTime) {
    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()), expectedTime);
}
 
Example 3
Source File: TCKDateTimeParseResolver.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_parse_fromField_SecondOfDay() {
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(SECOND_OF_DAY).toFormatter();
    TemporalAccessor acc = fmt.parse("864");
    assertEquals(acc.isSupported(SECOND_OF_DAY), 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_DAY), 864L);
    assertEquals(acc.getLong(NANO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MICRO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MILLI_OF_SECOND), 0L);
}
 
Example 4
Source File: TCKDateTimeFormatter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_resolverFields_emptyList() throws Exception {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(YEAR).toFormatter().withResolverFields();
    TemporalAccessor parsed = f.parse("2012");
    assertEquals(parsed.isSupported(YEAR), false);  // not in the list of resolverFields
}
 
Example 5
Source File: TCKDateTimeParseResolver.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 6
Source File: TestDateTimeFormatter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_parsed_toString_resolvedTime() {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("HH:mm:ss");
    TemporalAccessor temporal = f.parse("11:30:56");
    String msg = temporal.toString();
    assertTrue(msg.contains("11:30:56"), msg);
}
 
Example 7
Source File: TCKResolverStyle.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "resolverStyle")
public void test_resolverStyle(String str, ResolverStyle style, Class<?> expectedEx, int year, int month, int day) {
    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    builder.appendValue(ChronoField.YEAR_OF_ERA);
    builder.appendLiteral("/");
    builder.appendValue(ChronoField.MONTH_OF_YEAR);
    builder.appendLiteral("/");
    builder.appendValue(ChronoField.DAY_OF_MONTH);

    Map<Long, String> eraMap = new HashMap<Long, String>();
    eraMap.put(1L, "CE");
    eraMap.put(0L, "BCE");
    DateTimeFormatter optionalFormatter = new DateTimeFormatterBuilder().appendLiteral(" ").appendText(ChronoField.ERA, eraMap).toFormatter();

    DateTimeFormatter formatter = builder.appendOptional(optionalFormatter).toFormatter();
    formatter = formatter.withResolverStyle(style);
    if (expectedEx == null) {
        TemporalAccessor accessor = formatter.parse(str);
        assertEquals(accessor.get(ChronoField.YEAR_OF_ERA), year);
        assertEquals(accessor.get(ChronoField.MONTH_OF_YEAR), month);
        assertEquals(accessor.get(ChronoField.DAY_OF_MONTH), day);
    } else {
        try {
            formatter.parse(str);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example 8
Source File: TCKLocalizedPrinterParser.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test(dataProvider="date")
public void test_date_parse(LocalDate date, FormatStyle dateStyle, int dateStyleOld, Locale locale) {
    DateFormat old = DateFormat.getDateInstance(dateStyleOld, locale);
    Date oldDate = new Date(date.getYear() - 1900, date.getMonthValue() - 1, date.getDayOfMonth());
    String text = old.format(oldDate);

    DateTimeFormatter f = builder.appendLocalized(dateStyle, null).toFormatter(locale);
    TemporalAccessor parsed = f.parse(text, pos);
    assertEquals(pos.getIndex(), text.length());
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(LocalDate.from(parsed), date);
}
 
Example 9
Source File: TCKDateTimeParseResolver.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="resolveTwoToDate")
public void test_resolveTwoToDate(TemporalField field1, long value1,
                                  TemporalField field2, long value2,
                                  LocalDate expectedDate) {
    String str = value1 + " " + value2;
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(field1).appendLiteral(' ')
            .appendValue(field2).toFormatter();

    TemporalAccessor accessor = f.parse(str);
    assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate);
    assertEquals(accessor.query(TemporalQueries.localTime()), null);
}
 
Example 10
Source File: TCKDateTimeFormatter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test(expected=DateTimeParseException.class)
public void test_parse_CharSequence_ParsePosition_parseError() {
    DateTimeFormatter test = DateTimeFormatter.ISO_DATE;
    ParsePosition pos = new ParsePosition(3);
    try {
        test.parse("XXX2012XXX", pos);
        fail();
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getErrorIndex(), 7);
        throw ex;
    }
}
 
Example 11
Source File: TCKDateTimeParseResolver.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void test_fieldResolvesToLocalTime() {
    LocalTime lt = LocalTime.of(12, 30, 40);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(lt)).toFormatter();
    TemporalAccessor accessor = f.parse("1234567890");
    assertEquals(accessor.query(TemporalQueries.localDate()), null);
    assertEquals(accessor.query(TemporalQueries.localTime()), lt);
}
 
Example 12
Source File: TCKDateTimeParseResolver.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_parse_fromField_SecondOfDay() {
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(SECOND_OF_DAY).toFormatter();
    TemporalAccessor acc = fmt.parse("864");
    assertEquals(acc.isSupported(SECOND_OF_DAY), 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_DAY), 864L);
    assertEquals(acc.getLong(NANO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MICRO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MILLI_OF_SECOND), 0L);
}
 
Example 13
Source File: TestDateTimeParsing.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "instantNoZone")
public void test_parse_instantNoZone_Instant(DateTimeFormatter formatter, String text, Instant expected) {
    TemporalAccessor actual = formatter.parse(text);
    assertEquals(Instant.from(actual), expected);
}
 
Example 14
Source File: TestDateTimeParsing.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "instantZones")
public void test_parse_instantZones_LDT(DateTimeFormatter formatter, String text, ZonedDateTime expected) {
    TemporalAccessor actual = formatter.parse(text);
    assertEquals(LocalDateTime.from(actual), expected.toLocalDateTime());
}
 
Example 15
Source File: TCKDateTimeFormatter.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=IndexOutOfBoundsException.class)
public void test_parse_CharSequence_ParsePosition_indexTooBig() {
    DateTimeFormatter test = DateTimeFormatter.ISO_DATE;
    test.parse("Text", new ParsePosition(5));
}
 
Example 16
Source File: TCKDateTimeFormatter.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=IndexOutOfBoundsException.class)
public void test_parse_CharSequence_ParsePosition_indexTooBig() {
    DateTimeFormatter test = DateTimeFormatter.ISO_DATE;
    test.parse("Text", new ParsePosition(5));
}
 
Example 17
Source File: LocalDate.java    From desugar_jdk_libs with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains an instance of {@code LocalDate} from a text string using a specific formatter.
 * <p>
 * The text is parsed using the formatter, returning a date.
 *
 * @param text  the text to parse, not null
 * @param formatter  the formatter to use, not null
 * @return the parsed local date, not null
 * @throws DateTimeParseException if the text cannot be parsed
 */
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.parse(text, LocalDate::from);
}
 
Example 18
Source File: YearMonth.java    From jdk8u-jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains an instance of {@code YearMonth} from a text string using a specific formatter.
 * <p>
 * The text is parsed using the formatter, returning a year-month.
 *
 * @param text  the text to parse, not null
 * @param formatter  the formatter to use, not null
 * @return the parsed year-month, not null
 * @throws DateTimeParseException if the text cannot be parsed
 */
public static YearMonth parse(CharSequence text, DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.parse(text, YearMonth::from);
}
 
Example 19
Source File: LocalDateTime.java    From Java8CN with Apache License 2.0 2 votes vote down vote up
/**
 * Obtains an instance of {@code LocalDateTime} from a text string using a specific formatter.
 * <p>
 * The text is parsed using the formatter, returning a date-time.
 *
 * @param text  the text to parse, not null
 * @param formatter  the formatter to use, not null
 * @return the parsed local date-time, not null
 * @throws DateTimeParseException if the text cannot be parsed
 */
public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.parse(text, LocalDateTime::from);
}
 
Example 20
Source File: Year.java    From jdk8u60 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains an instance of {@code Year} from a text string using a specific formatter.
 * <p>
 * The text is parsed using the formatter, returning a year.
 *
 * @param text  the text to parse, not null
 * @param formatter  the formatter to use, not null
 * @return the parsed year, not null
 * @throws DateTimeParseException if the text cannot be parsed
 */
public static Year parse(CharSequence text, DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.parse(text, Year::from);
}