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

with Methods: Replacing Specific Fields

Learn to use withYear(), withMonth(), withDayOfMonth() to create new instances with specific fields replaced while keeping others.

with Methods: Replacing Specific Fields

What you'll learn: How to create modified copies of date-time objects by replacing specific fields while keeping all others unchanged.

The Core Idea

You've learned that date-time objects are immutable—every modification creates a new instance. While plus() and minus() adjust values relative to the current state, the with family of methods lets you set fields to absolute values. Think of it like using "Find and Replace" in a document: you're swapping out one specific piece while preserving everything else.

Common with Methods

LocalDate provides:

  • withYear(int year) - Replace the year
  • withMonth(int month) - Replace the month (1-12)
  • withDayOfMonth(int dayOfMonth) - Replace the day

LocalTime and LocalDateTime offer similar methods for hours, minutes, seconds, and nanoseconds.

How It Works

LocalDate original = LocalDate.of(2024, 3, 15);
// 2024-03-15

LocalDate newYear = original.withYear(2025);
// 2025-03-15 (only year changed)

LocalDate newMonth = original.withMonth(12);
// 2024-12-15 (only month changed)

LocalDate newDay = original.withDayOfMonth(1);
// 2024-03-01 (only day changed)

// Chain them together
LocalDate modified = original
    .withYear(2025)
    .withMonth(1)
    .withDayOfMonth(1);
// 2025-01-01

Why Use with Methods?

When you need to create a date with one field changed but don't want to reconstruct the entire object manually. For example, "get the first day of this month" is simply date.withDayOfMonth(1) rather than extracting year and month, then creating a new LocalDate.

Key Takeaway: with methods create new instances with specific fields replaced by absolute values, providing precise control over individual date-time components while maintaining immutability.