Java yearMonth withYear()方法及示例

Java yearMonth withYear()方法及示例

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

语法

public YearMonth withYear(int year)

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

返回值: 该方法返回一个基于该年月和所要求的年份的YearMonth。

异常: 如果年份值无效,该方法会抛出 DateTimeException

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

程序1 :

// 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

程序2

// 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: //docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#withYear(int)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程