Friday, December 12, 2025
HomeLanguagesJavaLocalDate withYear() method in Java with Examples

LocalDate withYear() method in Java with Examples

The withYear() method of LocalDate class in Java returns a copy of this LocalDate with the year altered.

Syntax:

public LocalDate withYear(int year)

Parameter: This method accepts a mandatory parameter year which specifies the year to set in the result which can be in the range from MIN_YEAR to MAX_YEAR.

Returns: The function returns a LocalDate based on this date with the requested year, not null.

Exceptions: The function throws a DateTimeException when the year value is invalid.

Below programs illustrate the LocalDate.withYear() method:

Program 1:




// Program to illustrate the withYear() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
  
        // Parses the date
        LocalDate dt1 = LocalDate.parse("2018-12-07");
        LocalDate result = dt1.withYear(2018);
  
        // Prints the date with year
        System.out.println("The date with year is: " + result);
    }
}


Output:

The date with year is: 2018-12-07

Program 2:




// Program to illustrate the withYear() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
  
        // Parses the date
        LocalDate dt1 = LocalDate.parse("2018-01-07");
        LocalDate result = dt1.withYear(2014);
  
        // Prints the date with year
        System.out.println("The date with year is: " + result);
    }
}


Output:

The date with year is: 2014-01-07

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#withYear(int)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32444 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11951 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12028 POSTS0 COMMENTS
Shaida Kate Naidoo
6945 POSTS0 COMMENTS
Ted Musemwa
7198 POSTS0 COMMENTS
Thapelo Manthata
6892 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS