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

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

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

ZonedDateTime类的withDayOfYear()方法,用于更改此 ZonedDateTime 中的年份,并在此操作后返回 ZonedDateTime 的副本。此方法在本地时间线上运行,更改本地日期的年份-time 并在此操作之后本地日期时间转换回 ZonedDateTime,使用区域 ID 获取偏移量。转换回 ZonedDateTime 时,如果本地日期时间重叠,则尽可能保留偏移量,否则将使用较早的偏移量。此实例是不可变的,不受此方法调用的影响。

句法:

public ZonedDateTime withDayOfYear(int dayOfYear)

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

返回值:此方法基于此日期时间与请求的日期返回ZonedDateTime

异常:如果年份值无效,或者年份对于年份无效,则此方法将引发DateTimeException

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

// Java program to demonstrate
// ZonedDateTime.withDayOfYear() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ZonedDateTime object
        ZonedDateTime zoneddatetime
            = ZonedDateTime.parse(
                "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
  
        // print instance
        System.out.println("ZonedDateTime before"
                           + " alter dayOfYear: "
                           + zoneddatetime);
  
        // alter dayOfYear to 200th day
        ZonedDateTime returnvalue
            = zoneddatetime.withDayOfYear(200);
  
        // print result
        System.out.println("ZonedDateTime after "
                           + "alter dayOfYear: "
                           + returnvalue);
    }
}
输出:

方案二:

// Java program to demonstrate
// ZonedDateTime.withDayOfYear() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ZonedDateTime object
        ZonedDateTime zoneddatetime
            = ZonedDateTime.parse(
                "2018-10-25T23:12:31.123+02:00[Europe/Paris]");
  
        // print instance
        System.out.println("ZonedDateTime before"
                           + " alter dayOfYear: "
                           + zoneddatetime);
  
        // alter dayOfYear to 365
        ZonedDateTime returnvalue
            = zoneddatetime.withDayOfYear(365);
  
        // print result
        System.out.println("ZonedDateTime after "
                           + "alter dayOfYear: "
                           + returnvalue);
    }
}
输出:

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