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

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

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

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

句法:

public OffsetDateTime withYear(int year)

参数:此方法接受单个参数year指定要在结果中设置的年份,范围从MIN_YEARMAX_YEAR

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

异常:当年份值无效时,程序会抛出DateTimeException

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

方案一:

// Java program to demonstrate the withYear() method
  
import java.time.OffsetDateTime;
  
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 year
        System.out.println("Date1 after altering year: "
                           + date1.withYear(2019));
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering year : 2019-12-12T13:30:30+05:00

方案二:

// Java program to demonstrate the withYear() method
  
import java.time.OffsetDateTime;
  
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 year
        System.out.println("Date1 after altering year: "
                           + date1.withYear(2010));
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering year: 2010-12-12T13:30:30+05:00

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