Custom TemporalQuery Field Extraction
Register a custom TemporalQuery on a formatter or parsed date to pull several typed fields in one pass, turning loose TemporalAccessor data into a small record.
Code
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalQuery;
public class BillingPeriod {
// custom TemporalQuery:field extraction 一次遍历抽出三个类型化字段
record Period(int year, Month month, int dayOfMonth) {}
static final TemporalQuery<Period> AS_PERIOD = temporal -> new Period(
temporal.get(ChronoField.YEAR),
Month.from(temporal),
temporal.get(ChronoField.DAY_OF_MONTH));
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 路径一:先解析成 LocalDate,再 query 抽取
Period fromParsed = LocalDate.parse("2026-02-14", formatter).query(AS_PERIOD);
System.out.println(fromParsed);
// 路径二:formatter.parse(text, query) 一步完成解析与抽取
Period direct = formatter.parse("2026-02-14", AS_PERIOD);
System.out.println(direct.year() + "/" + direct.month() + "/" + direct.dayOfMonth());
}
}The structure at work
The moving parts are the classes BillingPeriod and Period and the function main.
What to watch for
- The toolchain covers it — nothing to resolve, nothing to fetch.
Using it
Signature: public static void main(String[] args)
Key statements
Period fromParsed = LocalDate.parse("2026-02-14", formatter).query(AS_PERIOD);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Period direct = formatter.parse("2026-02-14", AS_PERIOD);
Interactive Tools for This Topic
FAQ
- How do you run Custom TemporalQuery Field Extraction?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.