📌  相关文章
📜  Java中的 OffsetDateTime withDayOfYear() 方法及示例

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

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

Java中 OffsetDateTime 类的withDayOfYear()方法返回此 OffsetDateTime 的副本,其中年份按参数中指定的方式更改。

句法:

public OffsetDateTime withDayOfYear(int dayOfYear)

参数:此方法接受单个参数dayOfYear ,该参数指定要在结果中设置的年份,范围为 1 到 365-366。

返回值:它返回一个基于此日期的 OffsetDateTime 和请求的一年中的哪一天,而不是 null。

异常:当年份值无效或该特定年份的月份的年份无效时,程序将引发DateTimeException

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

方案一:

// Java program to demonstrate the withDayOfYear() method
  
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Parses the date1
        OffsetDateTime date1
            = OffsetDateTime
                  .parse(
                      "2018-12-12T13:30:30+05:00");
  
        // Prints dates
        System.out.println("Date1: " + date1);
  
        // Changes the day of year
        System.out.println("Date1 after altering day-of-year: "
                           + date1.withDayOfYear(32));
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering day-of-year: 2018-02-01T13:30:30+05:00

方案二:

// Java program to demonstrate the withDayOfYear() method
  
import java.time.OffsetDateTime;
  
public class GFG {
    public static void main(String[] args)
    {
        try {
            // Parses the date1
            OffsetDateTime date1
                = OffsetDateTime
                      .parse(
                          "2018-12-12T13:30:30+05:00");
  
            // Prints dates
            System.out.println("Date1: " + date1);
  
            // Changes the day of year
            System.out.println("Date1 after altering day-of-year: "
                               + date1.withDayOfYear(367));
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Exception: java.time.DateTimeException:
           Invalid value for DayOfYear
           (valid values 1 - 365/366): 367

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