实现说明
parseBest 日期解析降级可以归结为类 ApiTimestampParser和函数 parse、main。
在这里做循环的是 for (String raw : new String[]。代码不会带着坏状态静默继续,守卫一命中就抛 IllegalArgumentException。
使用要点
- 运行整个文件:
main会依次驱动parse。
常见问题
前置条件不成立会发生什么?
代码会抛出 IllegalArgumentException。请在调用点处理,或有意让它向上传播。
「parseBest 日期解析降级」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
入口签名:static LocalDateTime parse(String input)
核心语句
throw new IllegalArgumentException("unsupported timestamp: " + input, rejected);
if (parsed instanceof OffsetDateTime offset) {
return offset.toLocalDateTime();
}
if (parsed instanceof LocalDateTime local) {
return local;
}
代码示例
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));
}
}
}