Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaLocalDateTime withDayOfYear() method in Java with Examples

LocalDateTime withDayOfYear() method in Java with Examples

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

Syntax:

public LocalDateTime withDayOfYear(int dayOfYear)

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

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

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

Below programs illustrate the LocalDateTime.withDayOfYear() method:

Program 1:




// Program to illustrate the withDayOfYear() 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 dayOfYear 1
        System.out.println("New LocalDateTime: "
                           + dt.withDayOfYear(1));
    }
}


Output:

Original LocalDateTime: 2018-11-30T12:54:35.320
New LocalDateTime: 2018-01-01T12:54:35.320

Program 2:




// Program to illustrate the withDayOfYear() 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 dayOfYear 365
        System.out.println("New LocalDateTime: "
                           + dt.withDayOfYear(365));
    }
}


Output:

Original LocalDateTime: 2015-04-06T10:15:30
New LocalDateTime: 2015-12-31T10:15:30

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

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

Most Popular

Recent Comments