DateTimeFormatterBuilder Defaults For Partial Input
Accept both full and abbreviated timestamps by combining optional pattern sections with parseDefaulting for fields the input omits.
Code
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
public class FlexibleTimestampParser {
public static void main(String[] args) {
// [ ] 是可选节:日可以整体缺席;uuuu 是宽松的年代字段
DateTimeFormatter date = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM[-dd]")
// 缺席的字段必须补默认值,否则解析不到完整日期会抛异常
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
System.out.println(LocalDate.parse("2026-11-15", date));
System.out.println(LocalDate.parse("2026-11", date));
DateTimeFormatter stamp = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd['T'HH:mm]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.toFormatter();
LocalDateTime full = LocalDateTime.parse("2026-11-15T09:30", stamp);
LocalDateTime midnight = LocalDateTime.parse("2026-11-15", stamp);
System.out.println(full);
System.out.println(midnight);
}
}Optional sections and defaults
The pattern uuuu-MM[-dd] marks the day as optional with brackets, and parseDefaulting(ChronoField.DAY_OF_MONTH, 1) supplies it when absent. The same builder accepts 2026-11-15 and 2026-11 and prints both LocalDate values.
Timestamps with optional time
The second formatter uses uuuu-MM-dd[’T’HH:mm] with defaults for HOUR_OF_DAY and MINUTE_OF_HOUR. LocalDateTime.parse(“2026-11-15T09:30”, stamp) keeps the given time, while parsing 2026-11-15 alone lands at 2026-11-15T00:00.
Why uuuu
uuuu is the proleptic year field that also accepts negative eras cleanly; with parseDefaulting it is the recommended base for partial-input parsing.
Interactive Tools for This Topic
FAQ
- Why is parseDefaulting required for the optional day?
- Without a default, an input that omits the bracketed section leaves DAY_OF_MONTH unset and the parse fails to resolve a complete date.
- What does the uuuu pattern provide over yyyy?
- uuuu is the proleptic-year field that handles eras uniformly, while yyyy is era-aware (year-of-era) and can shift values around the epoch.
Report a problem with this exampleOpens a pre-filled issue on GitHub.