Open In App

LocalDateTime withYear() method in Java with Examples

Last Updated : 30 Nov, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

The withYear() method of LocalDateTime class in Java is used to get a copy of this LocalDateTime with the year changed to the year passed as the parameter to this method. The remaining values of this LocalDateTime remains the same.

Syntax:

public LocalDateTime withYear(int year)

Parameter: This method accepts a single mandatory parameter year which specifies the year to be set in the resultant LocalDateTime instance. The value of this year can range from MIN_YEAR to MAX_YEAR.

Returns: The function returns a LocalDateTime instance with the year changed to the year passed as the parameter to this method. The remaining values of this LocalDateTime remains the same.

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

Below programs illustrate the LocalDateTime.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)
    {
        // Get the LocalDateTime instance
        LocalDateTime dt = LocalDateTime.now();
  
        // Get the String representation of this LocalDateTime
        System.out.println("Original LocalDateTime: "
                           + dt.toString());
  
        // Get a new LocalDateTime with year 1998
        System.out.println("New LocalDateTime: "
                           + dt.withYear(1998));
    }
}


Output:

Original LocalDateTime: 2018-11-30T10:35:17.833
New LocalDateTime: 1998-11-30T10:35:17.833

Program 2:




// Program to illustrate the withYear() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Get the LocalDateTime instance
        LocalDateTime dt
            = LocalDateTime
                  .parse("2015-04-06T10:15:30");
  
        // Get the String representation of this LocalDateTime
        System.out.println("Original LocalDateTime: "
                           + dt.toString());
  
        // Get a new LocalDateTime with year 20129
        System.out.println("New LocalDateTime: "
                           + dt.withYear(20129));
    }
}


Output:

Original LocalDateTime: 2015-04-06T10:15:30
New LocalDateTime: +20129-04-06T10:15:30

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads