Java LocalDate Class | withYear() method with Example

LocalDate Class withYear() method: Here, we are going to learn about the withYear() method of LocalDate Class with its syntax and example.
Submitted by Preeti Jain, on June 02, 2020

LocalDate Class withYear() method

  • withYear() method is available in java.time package.
  • withYear() method is used to update this LocalDate object with the given year.
  • withYear() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • withYear() method may throw an exception at the time of representing LocalDate with the given year.
    DateTimeException: This exception may throw when the given parameter is not valid.

Syntax:

    public LocalDate withYear(int yyyy_val);

Parameter(s):

  • int yyyy_val – represents year to update this LocalDate and the number of months in a year range starts from [1 to 12].

Return value:

The return type of this method is LocalDate, it returns the LocalDate that holds the value updated the given year in this object.

Example:

// Java program to demonstrate the example // of withYear(int yyyy_val) method of LocalDate import java.time.*; public class WithYearOfLocalDate { public static void main(String args[]) { int year = 2006; // Instantiates two LocalDate LocalDate l_da1 = LocalDate.parse("2007-04-04"); LocalDate l_da2 = LocalDate.of(2008, Month.FEBRUARY, 06); // Display l_da1,l_da2 System.out.println("LocalDate l_da1,l_da2 : "); System.out.println("l_da1: " + l_da1); System.out.println("l_da2: " + l_da2); System.out.println("year to update: " + year); System.out.println(); // Here, this method updates year // with the given value in this // LocalDate l_da1 LocalDate l_date = l_da1.withYear(year); // Display l_date System.out.println("l_da1.withYear(year): " + l_date); // Here, this method updates year // with the given value in this // LocalDate l_da2 l_date = l_da2.withYear(year); // Display l_date System.out.println("l_da2.withYear(year): " + l_date); } }

Output

LocalDate l_da1,l_da2 : 
l_da1: 2007-04-04
l_da2: 2008-02-06
year to update: 2006

l_da1.withYear(year): 2006-04-04
l_da2.withYear(year): 2006-02-06


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.