Javaexercise.com

Get LocalDateTime With The Year Altered In Java

Altering the year of local date-time returns a copy of the same date with the new year.

In this article, we will use the withYear() method of the LocalDateTime class to alter the year of any local date-time.

Getting LocalDateTime by altering the year in Java

Here, we used the now() method to get the current local date-time and we altered the year by setting the value to the withYear() method.

package javaexample;
/* 
 *  Code example to get localdatetime with the specified years in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// Current date and time
		LocalDateTime date = LocalDateTime.now();

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get new datetime with altered years
		LocalDateTime newDate = date.withYear(2020);

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T13:02:59.972878722
New date : 2020-03-17T13:02:59.972878722

 

Now,  let's have a look at this method signature:

public LocalDateTime withYear(int year)

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns a copy of localdatetime after altering the specified year.

Parameters: It takes a single int type value. It must be in range(MIN_YEAR to MAX_YEAR)

Exceptions: It throws a DateTimeException if the year value is invalid.

 

Let's check by passing the invalid year value to the withYear() method.

package javaexample;
/* 
 *  Code example to get localdatetime with the specified years in Java
 */
import java.time.LocalDateTime;
import java.time.Year;
public class JExercise {
	public static void main(String[] args) {		

		// Current date and time
		LocalDateTime date = LocalDateTime.now();

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get new datetime with altered years
		LocalDateTime newDate = date.withYear(Year.MAX_VALUE); // max range

		// Display new date
		System.out.println("New date : "+newDate);

		// Get new datetime with altered years
		newDate = date.withYear(Year.MAX_VALUE+10); // invalid range

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T13:05:54.300681740
New date : +999999999-03-17T13:05:54.300681740
Exception in thread "main" java.time.DateTimeException: Invalid value for Year (valid values -999999999 - 999999999): 1000000009