java.time.format.DateTimeParseException Java Examples

The following examples show how to use java.time.format.DateTimeParseException. 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: OerGeneralizedTimeCodec.java    From java-ilp-core with Apache License 2.0 6 votes vote down vote up
@Override
public OerGeneralizedTime read(CodecContext context, InputStream inputStream) throws IOException {
  Objects.requireNonNull(context);
  Objects.requireNonNull(inputStream);

  final String timeString = context.read(OerIA5String.class, inputStream).getValue();

  if (timeString.length() != 19 || !timeString.endsWith("Z")) {
    throw new IllegalArgumentException(
        "Interledger GeneralizedTime only supports values in the format 'YYYYMMDDTHHMMSS.fffZ',"
            + " value " + timeString + " is invalid.");
  }

  try {
    final Instant value = Instant.from(generalizedTimeFormatter.parse(timeString));
    return new OerGeneralizedTime(value);
  } catch (DateTimeParseException dtp) {
    throw new IllegalArgumentException(
        "Interledger GeneralizedTime only supports values in the format 'YYYYMMDDTHHMMSS.fffZ', "
            + "value " + timeString + " is invalid.",
        dtp);
  }
}
 
Example #2
Source File: TCKIsoFields.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "parseLenientWeek")
public void test_parse_parseLenientWeek_SMART(String str, LocalDate expected, boolean smart) {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':')
            .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral(':')
            .appendValue(DAY_OF_WEEK)
            .toFormatter().withResolverStyle(ResolverStyle.SMART);
    if (smart) {
        LocalDate parsed = LocalDate.parse(str, f);
        assertEquals(parsed, expected);
    } else {
        try {
            LocalDate.parse(str, f);
            fail("Should have failed");
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
Example #3
Source File: TCKDateTimeParseResolver.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="resolveClockHourOfDay")
public void test_resolveClockHourOfDay(ResolverStyle style, long value, Integer expectedHour, int expectedDays) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_DAY).toFormatter();

    if (expectedHour != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(expectedHour, 0));
        assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
Example #4
Source File: TCKDateTimeParseResolver.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="resolveFourToTime")
public void test_resolveThreeToTime(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).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.minusNanos(nano), "ResolverStyle: " + s);
            assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), excessPeriod, "ResolverStyle: " + s);
        } else {
            try {
                f.withResolverStyle(style).parse("");
                fail();
            } catch (DateTimeParseException ex) {
                // expected
            }
        }
    }
}
 
Example #5
Source File: TCKIsoFields.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "parseLenientQuarter")
public void test_parse_parseLenientQuarter_SMART(String str, LocalDate expected, boolean smart) {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(YEAR).appendLiteral(':')
            .appendValue(IsoFields.QUARTER_OF_YEAR).appendLiteral(':')
            .appendValue(IsoFields.DAY_OF_QUARTER)
            .toFormatter().withResolverStyle(ResolverStyle.SMART);
    if (smart) {
        LocalDate parsed = LocalDate.parse(str, f);
        assertEquals(parsed, expected);
    } else {
        try {
            LocalDate.parse(str, f);
            fail("Should have failed");
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
Example #6
Source File: TemporalIntervalRelationFunction.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public Value evaluate(final ValueFactory valueFactory, final Value... args) throws ValueExprEvaluationException {
    if (args.length != 2) {
        throw new ValueExprEvaluationException(getURI() + " requires exactly 2 arguments, got " + args.length);
    }

    final String[] strInterval = args[1].stringValue().split("/");
    if (strInterval.length != 2) {
        throw new ValueExprEvaluationException(getURI() + " requires the second argument: " + args[1] + " to be 2 dates seperated by a \'/\'");
    }
    try {
        final ZonedDateTime date1 = ZonedDateTime.parse(args[0].stringValue());
        final ZonedDateTime[] interval = new ZonedDateTime[] {
                ZonedDateTime.parse(strInterval[0]),
                ZonedDateTime.parse(strInterval[1])
        };
        final boolean result = relation(date1, interval);

        return valueFactory.createLiteral(result);
    } catch (final DateTimeParseException e) {
        throw new ValueExprEvaluationException("Date/Times provided must be of the ISO-8601 format. Example: 2007-04-05T14:30Z");
    }
}
 
Example #7
Source File: JapanEraNameCompatTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testFormatParseEraName() {
    LocalDate date = LocalDate.of(2019, 5, 1);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd GGGG");
    formatter = formatter.withChronology(JapaneseChronology.INSTANCE);

    int num = 0;
    for (Locale locale : Calendar.getAvailableLocales()) {
        formatter = formatter.withLocale(locale);
        try {
            LocalDate.parse(date.format(formatter), formatter);
        } catch (DateTimeParseException e) {
            // If an array is defined for Japanese eras in java.time resource,
            // but an era entry is missing, format fallback to English name
            // while parse throw DateTimeParseException.
            num++;
            System.out.println("Missing java.time resource data for locale: " + locale);
        }
    }
    if (num > 0) {
        throw new RuntimeException("Missing java.time data for " + num + " locales");
    }
}
 
Example #8
Source File: TCKDateTimeParseResolver.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="resolveClockHourOfDay")
public void test_resolveClockHourOfDay(ResolverStyle style, long value, Integer expectedHour, int expectedDays) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_DAY).toFormatter();

    if (expectedHour != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(expectedHour, 0));
        assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
Example #9
Source File: LimsFactory.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
@VisibleForTesting
static Map<String, LocalDate> readPreLimsArrivalDateTsv(@NotNull String preLimsArrivalDatesTsv) throws IOException {
    Map<String, LocalDate> arrivalDatesPerSampleId = Maps.newHashMap();
    List<String> lines = Files.lines(Paths.get(preLimsArrivalDatesTsv)).collect(Collectors.toList());
    for (String line : lines) {
        String[] parts = line.split(FIELD_SEPARATOR);

        if (parts.length == 2) {
            String sampleId = parts[0].trim();
            String arrivalDateString = parts[1].trim();
            LocalDate arrivalDate;
            try {
                arrivalDate = LocalDate.parse(arrivalDateString, LimsConstants.DATE_FORMATTER);
            } catch (DateTimeParseException exc) {
                LOGGER.warn("Could not parse date in pre-HMF arrival date csv: {}", arrivalDateString);
                arrivalDate = null;
            }
            arrivalDatesPerSampleId.put(sampleId, arrivalDate);
        } else {
            LOGGER.warn("Invalid line in pre-HMF arrival date csv: {}", line);
        }
    }
    return arrivalDatesPerSampleId;
}
 
Example #10
Source File: TCKDateTimeParseResolver.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="resolveClockHourOfAmPm")
public void test_resolveClockHourOfAmPm(ResolverStyle style, long value, Integer expectedValue) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_AMPM).toFormatter();

    if (expectedValue != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), null);
        assertEquals(accessor.isSupported(CLOCK_HOUR_OF_AMPM), false);
        assertEquals(accessor.isSupported(HOUR_OF_AMPM), true);
        assertEquals(accessor.getLong(HOUR_OF_AMPM), expectedValue.longValue());
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
Example #11
Source File: HafasConverter.java    From pt2matsim with GNU General Public License v2.0 6 votes vote down vote up
public static void run(String hafasFolder, TransitSchedule schedule, CoordinateTransformation transformation, Vehicles vehicles, String chosenDateString) throws IOException {
	if(!hafasFolder.endsWith("/")) hafasFolder += "/";

	// 3a. Get start_fahrplan date
	LocalDate fahrplanStartDate = ECKDATENReader.getFahrPlanStart(hafasFolder);
	LocalDate fahrplanEndDate = ECKDATENReader.getFahrPlanEnd(hafasFolder);
	try {
		LocalDate chosenDate = ECKDATENReader.getDate(chosenDateString);

		if (chosenDate.isBefore(fahrplanStartDate) || chosenDate.isAfter(fahrplanEndDate)) {
			throw new IllegalArgumentException(
					String.format("Chosen date %s is outside fahrplan period: (%s, %s)", chosenDate, fahrplanStartDate, fahrplanEndDate)
			);
		}

		int dayNr = (int) ChronoUnit.DAYS.between(fahrplanStartDate, chosenDate);
		run(hafasFolder, schedule, transformation, vehicles, dayNr);

	} catch (DateTimeParseException ex) {
		throw new IllegalArgumentException(
				"Format of chosen date (should be dd.MM.yyyy) is invalid: " + chosenDateString
		);
	}
}
 
Example #12
Source File: ZonedDateTimeReadConverter.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
@Override
public ZonedDateTime convert(String value) {
    ZonedDateTime result = null;

    try {
        if (log.isTraceEnabled()) {
            log.trace("Converting String {} to ZonedDateTime", value);
        }

        result = ZonedDateTime.parse(value);
    } catch (DateTimeParseException e) {
        log.error("{} could not be converted to java.time.ZonedDateTime", value);
    }

    return result;
}
 
Example #13
Source File: QueryValidator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Instant convertDateTime(Attribute attr, Object value) {
  if (value instanceof Instant) {
    return (Instant) value;
  }

  if (value == null) {
    return null;
  }

  // try to convert value
  Instant dateValue;
  if (value instanceof String) {
    String paramStrValue = (String) value;
    try {
      dateValue = MolgenisDateFormat.parseInstant(paramStrValue);
    } catch (DateTimeParseException e) {
      throw new MolgenisValidationException(
          new ConstraintViolation(
              format(
                  FAILED_TO_PARSE_ATTRIBUTE_AS_DATETIME_MESSAGE, attr.getName(), paramStrValue)));
    }
  } else {
    throw new MolgenisValidationException(
        new ConstraintViolation(
            format(
                "Attribute [%s] value is of type [%s] instead of [%s] or [%s]",
                attr.getName(),
                value.getClass().getSimpleName(),
                String.class.getSimpleName(),
                Instant.class.getSimpleName())));
  }
  return dateValue;
}
 
Example #14
Source File: TCKDuration.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void factory_parse_minus(String text, long expectedSeconds, int expectedNanoOfSecond) {
    Duration test;
    try {
        test = Duration.parse("-" + text);
    } catch (DateTimeParseException ex) {
        assertEquals(expectedSeconds == Long.MIN_VALUE, true);
        return;
    }
    // not inside try/catch or it breaks test
    assertEquals(test, Duration.ofSeconds(expectedSeconds, expectedNanoOfSecond).negated());
}
 
Example #15
Source File: LocalTimeConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object fromString(final String str) {
    try {
        return LocalTime.parse(str);
    } catch (final DateTimeParseException e) {
        final ConversionException exception = new ConversionException("Cannot parse value as local time", e);
        exception.add("value", str);
        throw exception;
    }
}
 
Example #16
Source File: TCKMonthDay.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="badParseData", expectedExceptions=DateTimeParseException.class)
public void factory_parse_fail(String text, int pos) {
    try {
        MonthDay.parse(text);
        fail(String.format("Parse should have failed for %s at position %d", text, pos));
    }
    catch (DateTimeParseException ex) {
        assertEquals(ex.getParsedString(), text);
        assertEquals(ex.getErrorIndex(), pos);
        throw ex;
    }
}
 
Example #17
Source File: TCKDateTimeFormatter.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parse_Query_String_parseErrorLongText() throws Exception {
    try {
        DATE_FORMATTER.parse("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", LocalDate::from);
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getMessage().contains("could not be parsed"), true);
        assertEquals(ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123..."), true);
        assertEquals(ex.getParsedString(), "ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789");
        assertEquals(ex.getErrorIndex(), 3);
        throw ex;
    }
}
 
Example #18
Source File: TCKPeriod.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="parseFailure", expectedExceptions=DateTimeParseException.class)
public void factory_parseFailures(String text) {
    try {
        Period.parse(text);
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getParsedString(), text);
        throw ex;
    }
}
 
Example #19
Source File: QuietPeriodIndicatorConfigurationProperties.java    From echo with Apache License 2.0 5 votes vote down vote up
private long parseIso(String iso) {
  if (Strings.isNullOrEmpty(iso)) {
    return -1;
  }
  try {
    Instant instant = Instant.from(ISO_INSTANT.parse(iso));
    return instant.toEpochMilli();
  } catch (DateTimeParseException e) {
    log.warn(
        "Unable to parse {} as an ISO date/time, disabling quiet periods: {}",
        iso,
        e.getMessage());
    return -1;
  }
}
 
Example #20
Source File: EntityRSQLNodeTraveller.java    From pnc with Apache License 2.0 5 votes vote down vote up
private <T extends Comparable<? super T>> T cast(String argument, Class<T> javaType) {
    if (javaType.isEnum()) {
        Class<? extends Enum> enumType = (Class<? extends Enum>) javaType;
        return (T) Enum.valueOf(enumType, argument);
    } else if (javaType == String.class) {
        return (T) argument;
    } else if (javaType == Integer.class || javaType == int.class) {
        return (T) Integer.valueOf(argument);
    } else if (javaType == Long.class || javaType == long.class) {
        return (T) Long.valueOf(argument);
    } else if (javaType == Boolean.class || javaType == boolean.class) {
        return (T) Boolean.valueOf(argument);
    } else if (javaType == Date.class) {
        try {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
            OffsetDateTime offsetDateTime = OffsetDateTime.parse(argument, timeFormatter);
            return (T) Date.from(Instant.from(offsetDateTime));
        } catch (DateTimeParseException ex) {
            throw new RSQLException(
                    "The datetime must be in the ISO-8601 format with timezone, e.g. 1970-01-01T00:00:00Z, was "
                            + argument,
                    ex);
        }
    } else {
        throw new UnsupportedOperationException(
                "The target type " + javaType + " is not known to the type converter.");
    }
}
 
Example #21
Source File: CommonUtils.java    From ad with Apache License 2.0 5 votes vote down vote up
public static LocalDate parseStringLocalDate(String dateString) throws AdException {
    for (String s : LOCAL_DATE_PARSE_PATTERN) {
        formatter = DateTimeFormatter.ofPattern(s, Locale.getDefault());
        try {
            return LocalDate.parse(dateString, formatter);
        } catch (DateTimeParseException ignored) {
        }
    }
    throw new AdException("unable parse String to LocalDate");
}
 
Example #22
Source File: EcrfItemGroup.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public LocalDate readItemDate(@NotNull String itemOID) {
    String ecrfValue = readItemString(itemOID);

    if (ecrfValue == null) {
        return null;
    }

    try {
        return LocalDate.parse(ecrfValue.trim(), DATE_FORMATTER);
    } catch (DateTimeParseException e) {
        return null;
    }
}
 
Example #23
Source File: DateUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the specified date string as an ISO 8601 date (yyyy-MM-dd'T'HH:mm:ss.SSSZZ)
 * and returns the {@link Instant} object.
 *
 * @param dateString
 *            The date string to parse.
 *
 * @return The parsed Instant object.
 */
public static Instant parseIso8601Date(String dateString) {
    // For EC2 Spot Fleet.
    if (dateString.endsWith("+0000")) {
        dateString = dateString
                         .substring(0, dateString.length() - 5)
                         .concat("Z");
    }

    try {
        return parseInstant(dateString, ISO_INSTANT);
    } catch (DateTimeParseException e) {
        return parseInstant(dateString, ALTERNATE_ISO_8601_DATE_FORMAT);
    }
}
 
Example #24
Source File: HtmlDateInput.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setValueAttribute(final String newValue) {
    try {
        if (hasFeature(JS_INPUT_SET_VALUE_DATE_SUPPORTED)) {
            FORMATTER_.parse(newValue);
        }
        super.setValueAttribute(newValue);
    }
    catch (final DateTimeParseException e) {
        // ignore
    }
}
 
Example #25
Source File: TCKDateTimeFormatters.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parse_basicIsoDate_largeYear() {
    try {
        LocalDate expected = LocalDate.of(123456, 6, 3);
        assertEquals(DateTimeFormatter.BASIC_ISO_DATE.parse("+1234560603", LocalDate::from), expected);
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getErrorIndex(), 0);
        assertEquals(ex.getParsedString(), "+1234560603");
        throw ex;
    }
}
 
Example #26
Source File: DurationParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Duration parse(String text) throws ParseException {
    try {
        return TimeUtils.parseDuration(text);
    } catch(DateTimeParseException e) {
        throw new FormatException();
    }
}
 
Example #27
Source File: QueryParamMapperHelper.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
public static LocalDateTime toDateTime(String value) {
    if (value.isEmpty()) return null;
    try {
        return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    } catch (DateTimeParseException e) {
        throw new BadRequestException("failed to parse local date time, value=" + value, "INVALID_HTTP_REQUEST", e);
    }
}
 
Example #28
Source File: Period.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static int parseNumber(CharSequence text, String str, int negate) {
    if (str == null) {
        return 0;
    }
    int val = Integer.parseInt(str);
    try {
        return Math.multiplyExact(val, negate);
    } catch (ArithmeticException ex) {
        throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0, ex);
    }
}
 
Example #29
Source File: TypeUtils.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the first DateTimeFormatter to parse the string, which represents a TIME
 * <p>
 * It's intended to be called at the start of a large formatting job so that it picks the write format and is not
 * called again. This is an optimization, because the older version, which will try multiple formatters was too
 * slow for large data sets.
 */
public static DateTimeFormatter getTimeFormatter(String timeValue) {
    for (DateTimeFormatter formatter : timeFormatters) {
        try {
            formatter.parse(timeValue);
            return formatter;
        } catch (DateTimeParseException e) {
            // ignore;
        }
    }
    return DATE_FORMATTER;
}
 
Example #30
Source File: TCKPeriod.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@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());
}