📜  Java中的 LocalDate withDayOfYear() 方法及示例

📅  最后修改于: 2022-05-13 01:55:15.123000             🧑  作者: Mango

Java中的 LocalDate withDayOfYear() 方法及示例

Java中LocalDate 类withDayOfYear()方法返回此 LocalDate 的副本,其中更改了年份。

句法:

public LocalDate withDayOfYear(int dayOfYear)

参数:此方法接受一个强制参数dayOfYear ,该参数指定要在结果中设置的年份,从 1 到 365-366。

返回:该函数返回一个基于此日期的 LocalDate 和请求的日期,而不是 null。

异常:当年份值无效时,该函数会引发DateTimeException

下面的程序说明了LocalDate.withDayOfYear()方法:

方案一:

// Program to illustrate the withDayOfYear() 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.withDayOfYear(01);
  
        // Prints the date with year
        System.out.println("The date with day of year is: " + result);
    }
}
输出:
The date with day of year is: 2018-01-01

方案二:

// Program to illustrate the withDayOfYear() method
// Exceptions
import java.util.*;
import java.time.*;
import java.time.temporal.ChronoField;
  
public class GfG {
    public static void main(String[] args)
    {
  
        try {
            // Parses the date
            LocalDate dt1 = LocalDate.parse("2018-12-07");
            LocalDate result = dt1.withDayOfYear(370);
  
            // Prints the date with year
            System.out.println("The date with month is: " + result);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.time.DateTimeException: Invalid value for DayOfYear (valid values 1 - 365/366): 370

参考: https: Java/time/LocalDate.html#withDayOfYear(int)