/** * Parses the given date and/or time, which may have an optional timezone. This method applies heuristic rules * for choosing if the object should be returned as a local date, or a date and time with timezone, <i>etc</i>. * The full date format is of the form "1970-01-01T00:00:00.000Z", but this method also accepts spaces in place * of 'T' as in "1970-01-01 00:00:00". * * @param text the character string to parse, or {@code null}. * @return a temporal object for the given text, or {@code null} if the given text was null. * @throws DateTimeParseException if the text can not be parsed as a date. * * @since 0.8 */ public static Temporal parseBest(final CharSequence text) { // Cast is safe if all QUERIES elements return a Temporal subtype. return (text != null) ? (Temporal) FORMAT.parseBest(toISO(text, 0, text.length()), QUERIES) : null; }
/** * Helper method for {@link #testToISO()}. */ private static String toISO(final String text) { return StandardDateFormat.toISO(text, 0, text.length()).toString(); }
/** * Parses the given text. This method accepts space as a separator between date and time. * * @param text the text to parse. * @return the date (never null). * @throws ParseException if the parsing failed. */ @Override public Date parse(final String text) throws ParseException { try { return toDate(format.parse(toISO(text, 0, text.length()))); } catch (DateTimeException | ArithmeticException e) { throw (ParseException) new ParseException(e.getLocalizedMessage(), getErrorIndex(e, null)).initCause(e); } }
/** * Parses the given date as an instant, assuming UTC timezone if unspecified. * * @param text the text to parse as an instant in UTC timezone by default. * @param lower index of the first character to parse. * @param upper index after the last character to parse. * @return the instant for the given text. * @throws DateTimeParseException if the text can not be parsed as a date. */ public static Instant parseInstantUTC(final CharSequence text, final int lower, final int upper) { TemporalAccessor date = FORMAT.parseBest(toISO(text, lower, upper), QUERIES); if (date instanceof Instant) { return (Instant) date; } final OffsetDateTime time; if (date instanceof LocalDateTime) { time = ((LocalDateTime) date).atOffset(ZoneOffset.UTC); } else { time = ((LocalDate) date).atTime(MIDNIGHT); } return time.toInstant(); }