Course contentsShow
← Java
Lesson 1842 of 2,87038. Date and Time API (java.time)Free lesson

Extracting Components: getYear, getMonth, getDayOfMonth

Learn to extract individual components from temporal objects using getter methods like getYear(), getHour(), and getDayOfWeek().

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 an int representing the year (e.g., 2024)
  • getMonth() returns a Month enum value (e.g., Month.JANUARY)
  • getDayOfMonth() returns an int from 1 to 31
  • getDayOfWeek() returns a DayOfWeek enum (e.g., DayOfWeek.MONDAY)

For LocalTime:

  • getHour() returns an int from 0 to 23
  • getMinute() returns an int from 0 to 59
  • getSecond() returns an int from 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.