ParseBest Date Parsing Fallback
parseBest tries queries from most to least complete: an optional-section formatter parses timestamps, datetimes, and date-only strings without try/catch chains.
Code
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
public class ApiTimestampParser {
// 可选段格式器:日期必选,T+时间可选,偏移量再可选
private static final DateTimeFormatter FLEXIBLE = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.optionalStart()
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.optionalStart()
.appendOffsetId()
.toFormatter();
// parseBest parsing fallback:按声明顺序尝试查询,最完整的类型优先,失败自动降级
static LocalDateTime parse(String input) {
try {
TemporalAccessor parsed = FLEXIBLE.parseBest(input,
OffsetDateTime::from, LocalDateTime::from, LocalDate::from);
if (parsed instanceof OffsetDateTime offset) {
return offset.toLocalDateTime();
}
if (parsed instanceof LocalDateTime local) {
return local;
}
return ((LocalDate) parsed).atStartOfDay();
} catch (DateTimeParseException rejected) {
throw new IllegalArgumentException("unsupported timestamp: " + input, rejected);
}
}
public static void main(String[] args) {
for (String raw : new String[] {
"2026-11-21T10:15:30+08:00",
"2026-11-21T10:15:30",
"2026-11-21",
}) {
System.out.println(raw + " -> " + parse(raw));
}
}
}Reading the snippet
The snippet is organized around the class ApiTimestampParser and the functions parse and main.
Iteration happens inside for (String raw : new String[] — everything outside it runs once. The failure path is explicit — IllegalArgumentException is raised when the guard condition holds.
What to watch for
- Any imports it has resolve to standard-library modules.
Applying it
The entry-point signature is static LocalDateTime parse(String input)
There are 1 call inside main — parse — executed top to bottom.
Statements that matter
throw new IllegalArgumentException("unsupported timestamp: " + input, rejected);
if (parsed instanceof OffsetDateTime offset) {
return offset.toLocalDateTime();
}
if (parsed instanceof LocalDateTime local) {
return local;
}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What happens if the preconditions do not hold?
- The code throws `IllegalArgumentException`. Handle it at the call site or let it propagate deliberately.
- How do you run ParseBest Date Parsing Fallback?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.