Java 类java.time.format.DateTimeParseException 实例源码

项目:jdk8u-jdk    文件:TCKDateTimeParseResolver.java   
@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
        }
    }
}
项目:JavaHomework    文件:PIMManager.java   
private PIMEntity CreatePIMAppointment(){
    System.out.println("Enter date for Appointmen item:(like 04/20/2017):");
    LocalDate AppointmenDate = null;
    String DateString = sc.nextLine();
    try{
        AppointmenDate = LocalDate.parse(DateString,DateTimeFormatter.ofPattern("MM/dd/yyyy"));
    }
    catch(DateTimeParseException e){
        System.out.println("Date Format Error, Go Back Create Item.");
        return null;
    }

    System.out.println("Enter date for Appointmen text:");
    String TextString = sc.nextLine();

    System.out.println("Enter date for Appointmen priority:");
    String PriorityString = sc.nextLine();

    return new PIMAppointment(TextString, AppointmenDate, PriorityString);
}
项目:JavaHomework    文件:PIMManager.java   
private PIMEntity CreatePIMTodo(){
    System.out.println("Enter date for todo item:(like 04/20/2017):");
    LocalDate TodoDate = null;
    String DateString = sc.nextLine();
    try{
        TodoDate = LocalDate.parse(DateString,DateTimeFormatter.ofPattern("MM/dd/yyyy"));
    }
    catch(DateTimeParseException e){
        System.out.println("Date Format Error, Go Back Create Item.");
        return null;
    }

    System.out.println("Enter date for todo text:");
    String TextString = sc.nextLine();

    System.out.println("Enter date for todo priority:");
    String PriorityString = sc.nextLine();

    return new PIMTodo(TextString, TodoDate, PriorityString);
}
项目:openjdk-jdk10    文件:Duration.java   
private static int parseFraction(CharSequence text, int start, int end, int negate) {
    // regex limits to [0-9]{0,9}
    if (start < 0 || end < 0 || end - start == 0) {
        return 0;
    }
    try {
        int fraction = Integer.parseInt(text, start, end, 10);

        // for number strings smaller than 9 digits, interpret as if there
        // were trailing zeros
        for (int i = end - start; i < 9; i++) {
            fraction *= 10;
        }
        return fraction * negate;
    } catch (NumberFormatException | ArithmeticException ex) {
        throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0).initCause(ex);
    }
}
项目:ARCLib    文件:LocalDateTimeFormType.java   
/**
 * Converts the value from all supported types to the internal one
 * @param propertyValue value with one type
 * @return value with internal type
 */
protected TypedValue convertValue(TypedValue propertyValue) {
    Object value = propertyValue.getValue();
    if(value == null) {
        return Variables.objectValue(null).create();
    }
    else if(value instanceof LocalDateTime) {
        return Variables.objectValue(value).create();
    }
    else if(value instanceof String) {
        try {
            return Variables.objectValue(LocalDateTime.parse((String) value)).create();
        } catch (DateTimeParseException e) {
            throw new ProcessEngineException("Could not parse value '"+value+"' as LocalDateTime.");
        }
    }
    else {
        throw new ProcessEngineException("Value '"+value+"' cannot be transformed into a LocalDateTime.");
    }
}
项目:gwt-jackson-apt    文件:DefaultDateFormat.java   
/**
 * Parse a date using the pattern given in parameter or {@link #DATE_FORMAT_STR_ISO8601} and the browser timezone.
 *
 * @param useBrowserTimezone when the date doesn't include timezone information use browser default or UTC.
 * @param pattern            pattern to use. If null, {@link #DATE_FORMAT_STR_ISO8601} will be used.
 * @param hasTz              whether the pattern includes timezone information. when null the pattern will be parsed to search it.
 * @param date               date to parse
 * @return the parsed date
 */
public Date parse(boolean useBrowserTimezone, String pattern, Boolean hasTz, String date) {
    if (null == pattern) {
        try {
            return parse(DefaultDateFormat.DATE_FORMAT_STR_ISO8601, date);
        }catch (DateTimeParseException e){
            return parse(DefaultDateFormat.DATE_FORMAT_STR_ISO8601_Z, date);
        }
    } else {
        String patternCacheKey = pattern + useBrowserTimezone;
        DateParser parser = CACHE_PARSERS.get(patternCacheKey);
        if (null == parser) {
            boolean patternHasTz = useBrowserTimezone || (hasTz == null ? hasTz(pattern) : hasTz.booleanValue());
            if (patternHasTz) {
                parser = new DateParser(pattern);
            } else {
                // the pattern does not have a timezone, we use the UTC timezone as reference
                parser = new DateParserNoTz(pattern);
            }
            CACHE_PARSERS.put(patternCacheKey, parser);
        }
        return parser.parse(date);
    }
}
项目:jdk8u-jdk    文件:TCKIsoFields.java   
@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
        }
    }
}
项目:jdk8u-jdk    文件:TCKIsoFields.java   
@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
        }
    }
}
项目:quilt    文件:OerGeneralizedTimeCodec.java   
@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);
  }
}
项目:mensa-api    文件:MenuWeekScraper.java   
@VisibleForTesting
Optional<LocalDate> getBaseDateFromString(String text) {
    Optional<LocalDate> result = Optional.empty();
    Matcher matcher = BASE_DATE_PATTERN.matcher(text);
    if (matcher.find()) {
        String dateAsString = matcher.group(1);
        try {
            result = Optional.of(LocalDate.parse(dateAsString, BASE_DATE_FORMATTER));
        } catch (DateTimeParseException e) {
            log.warn("Failed to parse base date from string: {}", text);
        }
    } else {
        log.warn("Failed to read base date from string: {}", text);
    }
    return result;
}
项目:mensa-api    文件:FilterInfo.java   
public static Optional<FilterInfo> fromString(String text) {
    Optional<FilterInfo> result = Optional.empty();
    String[] parts = StringUtils.split(text, ',');
    if (parts != null && parts.length == 3) {
        String value = parts[0];
        String mensaId = parts[1];
        String dateString = parts[2];
        try {
            LocalDate date = LocalDate.parse(dateString, DATE_TIME_FORMATTER);
            result = Optional.of(FilterInfo.of(value, mensaId, date));
        } catch (DateTimeParseException e) {
            log.info("Failed to parse local date from \"{}\": {}", dateString, e.getMessage());
        }
    }
    return result;
}
项目:jdk8u-jdk    文件:TCKDateTimeParseResolver.java   
@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
        }
    }
}
项目:jdk8u-jdk    文件:TCKDateTimeParseResolver.java   
@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
            }
        }
    }
}
项目:device-bluetooth    文件:ScheduleContext.java   
private ZonedDateTime parseTime(String time) {
  // TODO : may support more than one format at some point
  DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
      .withZone(ZoneId.systemDefault());
  ZonedDateTime zdt = null;

  try {
    zdt = ZonedDateTime.parse(time, dtf);
  } catch (DateTimeParseException e) {
    logger.debug("parseTime() failed to parse '" + time + "'");
    // throw an exception
    // mark as complete (via max iterations?)
  }

  return zdt;
}
项目:jdk8u-jdk    文件:TCKDateTimeParseResolver.java   
@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
        }
    }
}
项目:optashift-employee-rostering    文件:MonthDay.java   
/**
 * Obtains an instance of {@code MonthDay} from a text string such as {@code --12-03}.
 * <p>
 * The string must represent a valid month-day. The format is {@code --MM-dd}.
 * 
 * @param text the text to parse such as "--12-03", not null
 * @return the parsed month-day, not null
 * @throws DateTimeParseException if the text cannot be parsed
 */
public static MonthDay parse(CharSequence text) {

  int length = text.length();
  int errorIndex = 0;
  Throwable cause = null;
  try {
    // "--MM-dd".length() == 7
    if ((length == 7) && (text.charAt(0) == '-') && (text.charAt(1) == '-') && (text.charAt(4) == '-')) {
      errorIndex = 2;
      String monthString = text.subSequence(2, 4).toString();
      int month = Integer.parseInt(monthString);
      errorIndex = 5;
      String dayString = text.subSequence(5, 7).toString();
      int day = Integer.parseInt(dayString);
      return of(month, day);
    }
  } catch (RuntimeException e) {
    cause = e;
  }
  throw new DateTimeParseException("Expected format --MM-dd", text, errorIndex, cause);
}
项目:optashift-employee-rostering    文件:LocalDateTime.java   
/**
 * Obtains an instance of {@code LocalDateTime} from a text string such as {@code 2007-12-03T10:15:30}.
 * <p>
 * The string must represent a valid date-time and is parsed using
 * {@link java.time.format.DateTimeFormatters#isoLocalDateTime()}.
 * 
 * @param text the text to parse such as "2007-12-03T10:15:30", not null
 * @return the parsed local date-time, not null
 * @throws DateTimeParseException if the text cannot be parsed
 */
public static LocalDateTime parse(CharSequence text) {

  // "YYYY-MM-ddTHH:mm".length() == 16, "YYYY-MM-ddTHH:mm:ss.SSSSSSSSS".length() == 29
  int length = text.length();
  if ((length >= 16) && (length <= 32)) {
    int timeStartIndex = 10;
    while (Character.toUpperCase(text.charAt(timeStartIndex)) != 'T') {
      timeStartIndex++;
      if (timeStartIndex >= length) {
        timeStartIndex = -1;
        break;
      }
    }
    if (timeStartIndex > 0) {
      LocalDate date = LocalDate.parse(text.subSequence(0, timeStartIndex));
      LocalTime time = LocalTime.parse(text.subSequence(timeStartIndex + 1, length));
      return new LocalDateTime(date, time);
    }
  }
  throw new DateTimeParseException("Expected format yyyy-MM-ddTHH:mm:ss", text, 0, null);
}
项目:optashift-employee-rostering    文件:PeriodParser.java   
private void parseDate(String s, int baseIndex) {

    this.index = 0;
    while (this.index < s.length()) {
      String value = parseNumber(s);
      if (this.index < s.length()) {
        char c = s.charAt(this.index);
        switch (c) {
          case 'Y':
            this.years = parseInt(value, baseIndex);
            break;
          case 'M':
            this.months = parseInt(value, baseIndex);
            break;
          case 'D':
            this.days = parseInt(value, baseIndex);
            break;
          default :
            throw new DateTimeParseException(
                "Period could not be parsed, unrecognized letter '" + c + ": " + this.text, this.text, baseIndex
                    + this.index);
        }
        this.index++;
      }
    }
  }
项目:xm-uaa    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:device-modbus    文件:ScheduleContext.java   
private ZonedDateTime parseTime(String time) {
    // TODO : may support more than one format at some point
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0]).withZone(ZoneId.systemDefault());
    ZonedDateTime zdt = null;
    try {
        zdt = ZonedDateTime.parse(time, dtf);
    } catch (DateTimeParseException e) {
        logger.debug("parseTime() failed to parse '" + time + "'");
        // throw an exception
        // mark as complete (via max iterations?)
    }
    return zdt;
}
项目:jhipster-microservices-example    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:jhipster-microservices-example    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:MTC_Labrat    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:StickyChunk    文件:CoreChunkLoaderConfig.java   
public Optional<Duration> getDuration() {
    try {
        return Optional.of(Duration.parse(duration));
    } catch (DateTimeParseException e) {
        if (!duration.equalsIgnoreCase("forever") || !duration.equalsIgnoreCase("infinite")) {
            StickyChunk.getInstance().getLogger()
                .warn(String.format("Duration (%s) of %s is malformed. Using 1d instead", duration, name));
            return Optional.of(Duration.ofDays(1));
        }
        return Optional.empty();
    }
}
项目:openjdk-jdk10    文件:TCKDateTimeFormatter.java   
@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;
    }
}
项目:openjdk-jdk10    文件:TCKYear.java   
@Test(dataProvider="badParseData", expectedExceptions=DateTimeParseException.class)
public void factory_parse_fail(String text, int pos) {
    try {
        Year.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;
    }
}
项目:Armory    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:xm-ms-dashboard    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:OperatieBRP    文件:DatumServiceImpl.java   
@Override
public LocalDate parseDate(final String dateString) throws StapMeldingException {
    try {
        return DatumFormatterUtil.vanXsdDatumNaarLocalDate(dateString);
    } catch (final DateTimeParseException pe) {
        LOGGER.warn("Datum kan niet geparsed worden: {}", dateString);
        throw new StapMeldingException(Regel.R1274, pe);
    }
}
项目:openjdk-jdk10    文件:TCKPeriod.java   
@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;
    }
}
项目:micrometer    文件:StringToDurationConverter.java   
@Override
public Duration convert(String source) {
    Duration duration = simpleParse(source);
    try {
        return duration == null ? Duration.parse(source) : duration;
    } catch(DateTimeParseException e) {
        throw new IllegalArgumentException("Cannot convert '" + source + "' to Duration", e);
    }
}
项目:openjdk-jdk10    文件:TCKIsoFields.java   
@Test(dataProvider = "parseLenientWeek", expectedExceptions = DateTimeParseException.class)
public void test_parse_parseLenientWeek_STRICT(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.STRICT);
    LocalDate.parse(str, f);
}
项目:date-time-converter-plugin    文件:DateTimeUtil.java   
public static boolean isDateTime(String text, String format) {
    try {
        ZonedDateTime.parse(text, DateTimeFormatter.ofPattern(format).withZone(ZoneOffset.UTC));
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}
项目:Java-9-Programming-Blueprints    文件:TimeToken.java   
public static TimeToken of(final String text) {
    String time = text.toLowerCase();
    if (NOW.equals(time)) {
        return new TimeToken(LocalTime.now());
    } else {
        try {
            // For hours < 10 (e.g., 1:30), the string will be less than 5 characters. LocalTime.parse(), though, requires, in its 
            // simplest form, HH:MM. If the string is less than 5 characters, we're going to add a zero at the beginning to put
            // the string in the correct format hopefully. If the string is truly an invalid format (e.g., '130'), then
            // LocalDate.parse() will fail, so there's no need to do sohpisticated validation here. We'll coerce the string as
            // needed to the correct length, then let the JDK do the heavy lifting.
            if (time.length() <5) {
                time = "0" + time;
            }
            if (time.contains("am") || time.contains("pm")) {
                final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                        .parseCaseInsensitive()
                        .appendPattern("h:mma")
                        .toFormatter();
                return new TimeToken(LocalTime.parse(time.replaceAll(" ", ""), formatter));
            } else {
                return new TimeToken(LocalTime.parse(time));
            }
        } catch (DateTimeParseException ex) {
            ex.printStackTrace();
            throw new DateCalcException("Invalid time format: " + text);
        }
    }
}
项目:sentry    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:optashift-employee-rostering    文件:OffsetDate.java   
/**
 * Obtains an instance of {@code OffsetDate} from a text string such as {@code 2007-12-03+01:00}.
 * <p>
 * The string must represent a valid date and is parsed using
 * {@link java.time.format.DateTimeFormatters#isoOffsetDate()}.
 * 
 * @param text the text to parse such as "2007-12-03+01:00", not null
 * @return the parsed offset date, not null
 * @throws DateTimeParseException if the text cannot be parsed
 */
public static OffsetDate parse(CharSequence text) {

  int length = text.length();
  // "yyyy-MM-ddZ".length() == 11, "yyyy-MM-ddXXXXX".length() == 15
  Throwable cause = null;
  try {
    if ((length >= 11) && (length <= 20)) {
      int zoneStartIndex = 10;
      while (!OffsetTime.isZoneStartCharacter(text.charAt(zoneStartIndex))) {
        zoneStartIndex++;
        if (zoneStartIndex >= length) {
          zoneStartIndex = -1;
          break;
        }
      }
      if (zoneStartIndex > 0) {
        LocalDate localDate = LocalDate.parse(text.subSequence(0, zoneStartIndex));
        ZoneOffset zoneOffset = ZoneOffset.of(text.subSequence(zoneStartIndex, length).toString());
        return new OffsetDate(localDate, zoneOffset);
      }
    }
  } catch (RuntimeException e) {
    cause = e;
  }
  throw new DateTimeParseException("Expected format yyyy-MM-ddXXXXX", text, 0, cause);
}
项目:jdk8u-jdk    文件:TCKDateTimeFormatter.java   
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parse_Query_String_parseError() throws Exception {
    try {
        DATE_FORMATTER.parse("ONE2012 07 XX", LocalDate::from);
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getMessage().contains("could not be parsed"), true);
        assertEquals(ex.getMessage().contains("ONE2012 07 XX"), true);
        assertEquals(ex.getParsedString(), "ONE2012 07 XX");
        assertEquals(ex.getErrorIndex(), 11);
        throw ex;
    }
}
项目:jdk8u-jdk    文件:TCKDateTimeParseResolver.java   
@Test(expectedExceptions = DateTimeParseException.class)
public void test_fieldResolvesToChronoZonedDateTime_overrideZone_wrongZone() {
    ZonedDateTime zdt = ZonedDateTime.of(2010, 6, 30, 12, 30, 0, 0, EUROPE_PARIS);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(zdt)).toFormatter();
    f = f.withZone(ZoneId.of("Europe/London"));
    f.parse("1234567890");
}
项目:pokeraidbot    文件:Utils.java   
public static LocalTime parseTime(User user, String timeString, LocaleService localeService) {
    LocalTime endsAtTime;
    try {
        timeString = preProcessTimeString(timeString);
        endsAtTime = LocalTime.parse(timeString, Utils.timeParseFormatter);
    } catch (DateTimeParseException | NullPointerException e) {
        throw new UserMessedUpException(user,
                localeService.getMessageFor(LocaleService.BAD_DATETIME_FORMAT, localeService.getLocaleForUser(user),
                        "HH:MM", timeString));
    }
    return endsAtTime;
}
项目:ProjectAres    文件:CommandUtils.java   
public static Duration getDuration(@Nullable String text, Duration def) throws CommandException {
    if(text == null) {
        return def;
    } else {
        try {
            return TimeUtils.parseDuration(text);
        } catch(DateTimeParseException e) {
            throw new TranslatableCommandException("command.error.invalidTimePeriod", text);
        }
    }
}