Extracting Components: getYear, getMonth, getDayOfMonth
What you'll learn: How to pull individual date and time components from temporal objects using built-in getter methods.
The Core Idea
Once you have a LocalDate, LocalTime, or LocalDateTime object, you often need to work with its individual pieces—like just the year, or just the hour. Java's Date and Time API provides simple getter methods to extract these components without any string parsing or complex logic.
Think of a temporal object like a structured box with labeled compartments. Each getter method opens a specific compartment and hands you its contents. You don't need to disassemble the entire box; you simply ask for what you need.
Common Component Extractors
For LocalDate:
getYear()returns anintrepresenting the year (e.g., 2024)getMonth()returns aMonthenum value (e.g.,Month.JANUARY)getDayOfMonth()returns anintfrom 1 to 31getDayOfWeek()returns aDayOfWeekenum (e.g.,DayOfWeek.MONDAY)
For LocalTime:
getHour()returns anintfrom 0 to 23getMinute()returns anintfrom 0 to 59getSecond()returns anintfrom 0 to 59
For LocalDateTime: You can use all the methods above since it combines both date and time.
Why This Matters
These getters let you perform conditional logic ("if the year is 2024..."), format output your own way, or pass specific values to other methods. They're straightforward, type-safe, and eliminate the fragile string manipulation that plagued older date APIs.
Key Takeaway: Use getter methods like getYear(), getMonth(), and getDayOfMonth() to extract individual components from temporal objects—they return strongly-typed values (ints or enums) that are easy to work with.