Search in sources :

Example 16 with DateTimeParseException

use of java.time.format.DateTimeParseException in project jdk8u_jdk by JetBrains.

the class Duration method parse.

//-----------------------------------------------------------------------
/**
     * Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}.
     * <p>
     * This will parse a textual representation of a duration, including the
     * string produced by {@code toString()}. The formats accepted are based
     * on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days
     * considered to be exactly 24 hours.
     * <p>
     * The string starts with an optional sign, denoted by the ASCII negative
     * or positive symbol. If negative, the whole period is negated.
     * The ASCII letter "P" is next in upper or lower case.
     * There are then four sections, each consisting of a number and a suffix.
     * The sections have suffixes in ASCII of "D", "H", "M" and "S" for
     * days, hours, minutes and seconds, accepted in upper or lower case.
     * The suffixes must occur in order. The ASCII letter "T" must occur before
     * the first occurrence, if any, of an hour, minute or second section.
     * At least one of the four sections must be present, and if "T" is present
     * there must be at least one section after the "T".
     * The number part of each section must consist of one or more ASCII digits.
     * The number may be prefixed by the ASCII negative or positive symbol.
     * The number of days, hours and minutes must parse to an {@code long}.
     * The number of seconds must parse to an {@code long} with optional fraction.
     * The decimal point may be either a dot or a comma.
     * The fractional part may have from zero to 9 digits.
     * <p>
     * The leading plus/minus sign, and negative values for other units are
     * not part of the ISO-8601 standard.
     * <p>
     * Examples:
     * <pre>
     *    "PT20.345S" -- parses as "20.345 seconds"
     *    "PT15M"     -- parses as "15 minutes" (where a minute is 60 seconds)
     *    "PT10H"     -- parses as "10 hours" (where an hour is 3600 seconds)
     *    "P2D"       -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
     *    "P2DT3H4M"  -- parses as "2 days, 3 hours and 4 minutes"
     *    "P-6H3M"    -- parses as "-6 hours and +3 minutes"
     *    "-P6H3M"    -- parses as "-6 hours and -3 minutes"
     *    "-P-6H+3M"  -- parses as "+6 hours and -3 minutes"
     * </pre>
     *
     * @param text  the text to parse, not null
     * @return the parsed duration, not null
     * @throws DateTimeParseException if the text cannot be parsed to a duration
     */
public static Duration parse(CharSequence text) {
    Objects.requireNonNull(text, "text");
    Matcher matcher = PATTERN.matcher(text);
    if (matcher.matches()) {
        // check for letter T but no time sections
        if ("T".equals(matcher.group(3)) == false) {
            boolean negate = "-".equals(matcher.group(1));
            String dayMatch = matcher.group(2);
            String hourMatch = matcher.group(4);
            String minuteMatch = matcher.group(5);
            String secondMatch = matcher.group(6);
            String fractionMatch = matcher.group(7);
            if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) {
                long daysAsSecs = parseNumber(text, dayMatch, SECONDS_PER_DAY, "days");
                long hoursAsSecs = parseNumber(text, hourMatch, SECONDS_PER_HOUR, "hours");
                long minsAsSecs = parseNumber(text, minuteMatch, SECONDS_PER_MINUTE, "minutes");
                long seconds = parseNumber(text, secondMatch, 1, "seconds");
                int nanos = parseFraction(text, fractionMatch, seconds < 0 ? -1 : 1);
                try {
                    return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos);
                } catch (ArithmeticException ex) {
                    throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0).initCause(ex);
                }
            }
        }
    }
    throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0);
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) Matcher(java.util.regex.Matcher)

Example 17 with DateTimeParseException

use of java.time.format.DateTimeParseException in project gerrit by GerritCodeReview.

the class CommentTimestampAdapter method read.

@Override
public Timestamp read(JsonReader in) throws IOException {
    String str = in.nextString();
    TemporalAccessor ta;
    try {
        ta = ISO_INSTANT.parse(str);
    } catch (DateTimeParseException e) {
        ta = LocalDateTime.from(FALLBACK.parse(str)).atZone(ZoneId.systemDefault());
    }
    return Timestamp.from(Instant.from(ta));
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) TemporalAccessor(java.time.temporal.TemporalAccessor)

Example 18 with DateTimeParseException

use of java.time.format.DateTimeParseException in project jdk8u_jdk by JetBrains.

the class TCKPeriod method factory_parse_minus.

@Test(dataProvider = "parseSuccess")
public void factory_parse_minus(String text, Period expected) {
    Period p = null;
    try {
        p = Period.parse("-" + text);
    } catch (DateTimeParseException ex) {
        assertEquals(expected.getYears() == Integer.MIN_VALUE || expected.getMonths() == Integer.MIN_VALUE || expected.getDays() == Integer.MIN_VALUE, true);
        return;
    }
    // not inside try/catch or it breaks test
    assertEquals(p, expected.negated());
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) Period(java.time.Period) Test(org.testng.annotations.Test)

Example 19 with DateTimeParseException

use of java.time.format.DateTimeParseException in project jdk8u_jdk by JetBrains.

the class TCKDateTimeParseResolver method test_resolveFourToTime.

@Test(dataProvider = "resolveFourToTime")
public void test_resolveFourToTime(ResolverStyle style, long hour, long min, long sec, long nano, LocalTime expectedTime, Period excessPeriod) {
    DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(HOUR_OF_DAY, hour).parseDefaulting(MINUTE_OF_HOUR, min).parseDefaulting(SECOND_OF_MINUTE, sec).parseDefaulting(NANO_OF_SECOND, nano).toFormatter();
    ResolverStyle[] styles = (style != null ? new ResolverStyle[] { style } : ResolverStyle.values());
    for (ResolverStyle s : styles) {
        if (expectedTime != null) {
            TemporalAccessor accessor = f.withResolverStyle(s).parse("");
            assertEquals(accessor.query(TemporalQueries.localDate()), null, "ResolverStyle: " + s);
            assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime, "ResolverStyle: " + s);
            assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), excessPeriod, "ResolverStyle: " + s);
        } else {
            try {
                f.withResolverStyle(style).parse("");
                fail();
            } catch (DateTimeParseException ex) {
            // expected
            }
        }
    }
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) TemporalAccessor(java.time.temporal.TemporalAccessor) ResolverStyle(java.time.format.ResolverStyle) DateTimeFormatter(java.time.format.DateTimeFormatter) DateTimeFormatterBuilder(java.time.format.DateTimeFormatterBuilder) Test(org.testng.annotations.Test)

Example 20 with DateTimeParseException

use of java.time.format.DateTimeParseException in project jdk8u_jdk by JetBrains.

the class TCKDateTimeParseResolver method test_resolveMinuteOfDay.

@Test(dataProvider = "resolveMinuteOfDay")
public void test_resolveMinuteOfDay(ResolverStyle style, long value, Integer expectedMinute, int expectedDays) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(MINUTE_OF_DAY).toFormatter();
    if (expectedMinute != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.ofSecondOfDay(expectedMinute * 60));
        assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
        // expected
        }
    }
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) TemporalAccessor(java.time.temporal.TemporalAccessor) DateTimeFormatter(java.time.format.DateTimeFormatter) DateTimeFormatterBuilder(java.time.format.DateTimeFormatterBuilder) Test(org.testng.annotations.Test)

Aggregations

DateTimeParseException (java.time.format.DateTimeParseException)29 DateTimeFormatter (java.time.format.DateTimeFormatter)15 Test (org.testng.annotations.Test)14 DateTimeFormatterBuilder (java.time.format.DateTimeFormatterBuilder)10 TemporalAccessor (java.time.temporal.TemporalAccessor)10 LocalDate (java.time.LocalDate)6 Instant (java.time.Instant)5 LocalDateTime (java.time.LocalDateTime)5 Duration (java.time.Duration)2 ResolverStyle (java.time.format.ResolverStyle)2 Matcher (java.util.regex.Matcher)2 Cache (com.github.benmanes.caffeine.cache.Cache)1 Caffeine (com.github.benmanes.caffeine.cache.Caffeine)1 Conference (com.github.lantoine.lamsadetools.conferences.Conference)1 AddressInfos (com.github.lantoine.lamsadetools.map.AddressInfos)1 GoogleItineraryMap (com.github.lantoine.lamsadetools.map.GoogleItineraryMap)1 UserDetails (com.github.lantoine.lamsadetools.setCoordinates.UserDetails)1 KvDouble (com.torodb.kvdocument.values.KvDouble)1 KvLong (com.torodb.kvdocument.values.KvLong)1 InstantKvInstant (com.torodb.kvdocument.values.heap.InstantKvInstant)1