📜  Java中的 YearMonth withYear() 方法及示例

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

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

YearMonth类的withYear(int year)方法用于使用作为参数传递的年份更改 YearMonth 对象的年份,然后该方法返回更改后的 YearMonth 的副本。此实例是不可变的,不受此方法调用的影响。

句法:

public YearMonth withYear(int year)

参数:此方法接受月份作为参数,即在返回的年月中设置的年份,从 MIN_YEAR 到 MAX_YEAR。

返回值:此方法根据请求的年份返回基于此年月的 YearMonth。

异常:如果年份值无效,此方法将引发DateTimeException

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

// Java program to demonstrate
// YearMonth.withYear() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a YearMonth object
        YearMonth yr
            = YearMonth.of(2019, 12);
  
        // print instance
        System.out.println("YearMonth before"
                           + " applying method: "
                           + yr);
  
        // apply withYear method of YearMonth class
        YearMonth updatedlocal = yr.withYear(2023);
  
        // print instance
        System.out.println("YearMonth after"
                           + " applying method: "
                           + updatedlocal);
    }
}
输出:
YearMonth before applying method: 2019-12
YearMonth after applying method: 2023-12

方案二:

// Java program to demonstrate
// YearMonth.withYear() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a YearMonth object
        YearMonth yr
            = YearMonth.of(2022, 7);
  
        // print instance
        System.out.println("YearMonth before"
                           + " applying method: "
                           + yr);
  
        // apply withYear method of YearMonth class
        YearMonth updatedlocal = yr.withYear(1992);
  
        // print instance
        System.out.println("YearMonth after"
                           + " applying method: "
                           + updatedlocal);
    }
}
输出:
YearMonth before applying method: 2022-07
YearMonth after applying method: 1992-07

参考资料: https: Java/time/YearMonth.html#withYear(int)