Java yearMonth withMonth()方法及示例
YearMonth 类的 withMonth(int month) 方法用来改变YearMonth对象的年月日,使用的是作为参数传递的月份,之后该方法返回改变后的YearMonth的副本。如果指定月份的月日无效,日将被调整为最后的有效月日。这个实例是不可改变的,不受这个方法调用的影响。
语法
public YearMonth withMonth(int month)
参数: 该方法接受 月份 作为参数,即在返回的年月中设置年月,从1(一月)到12(十二月)。
返回值: 该方法返回一个基于该年月的YearMonth,该年月为要求的月份。
异常: 如果年月的值无效,该方法会抛出 DateTimeException 。
下面的程序说明了withMonth()方法:
程序1 :
// Java program to demonstrate
// YearMonth.withMonth() 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 withMonth method of YearMonth class
YearMonth updatedlocal = yr.withMonth(1);
// print instance
System.out.println("YearMonth after"
+ " applying method: "
+ updatedlocal);
}
}
输出。
YearMonth before applying method: 2019-12
YearMonth after applying method: 2019-01
程序2
// Java program to demonstrate
// YearMonth.withMonth() 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 withMonth method of YearMonth class
YearMonth updatedlocal = yr.withMonth(12);
// print instance
System.out.println("YearMonth after"
+ " applying method: "
+ updatedlocal);
}
}
输出。
YearMonth before applying method: 2022-07
YearMonth after applying method: 2022-12
参考文献: https: //docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#withMonth(int)