Java MonthDay with()方法及示例
MonthDay 类的 with(Month month) 方法用于改变MonthDay对象的年月日,使用的是作为参数传递的月份,之后该方法返回改变后的MonthDay副本。如果在改变操作后,指定月份的月日值无效,则该日将被调整为最后的有效月日。
语法
public MonthDay with(Month month)
参数: 该方法接受 月份 作为参数,它是要在返回的月日中设置的年月份。
返回值: 该方法返回一个基于该月日和所要求的月份的月日。
以下程序说明了with()方法:
程序1 :
// Java program to demonstrate
// MonthDay.with() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a MonthDay object
MonthDay monthday
= MonthDay.of(8, 28);
// print instance
System.out.println("MonthDay before"
+ " applying method: "
+ monthday);
// apply with method of MonthDay class
MonthDay updatedlocal
= monthday.with(Month.OCTOBER);
// print instance
System.out.println("MonthDay after"
+ " applying method: "
+ updatedlocal);
}
}
输出。
MonthDay before applying method: --08-28
MonthDay after applying method: --10-28
程序2
// Java program to demonstrate
// MonthDay.with() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a MonthDay object
MonthDay monthday
= MonthDay.of(10, 31);
// print instance
System.out.println("MonthDay before"
+ " applying method: "
+ monthday);
// apply with method of MonthDay class
MonthDay updatedlocal
= monthday.with(Month.FEBRUARY);
// print instance
System.out.println("MonthDay after"
+ " applying method: "
+ updatedlocal);
}
}
输出。
MonthDay before applying method: --10-31
MonthDay after applying method: --02-29
**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/time/MonthDay.html#with(java.time.Month)