Java中的 MonthDay with() 方法及示例
MonthDay类的with(Month month)方法用于更改 MonthDay 对象的月份,使用作为参数传递的月份,在该方法之后返回更改后的 MonthDay 的副本。如果月份的日期值对更改操作后的指定月份,日期将调整为最后一个有效日期。
句法:
public MonthDay with(Month month)
参数:此方法接受月份作为参数,该参数是要在返回的月日中设置的月份。
返回值:此方法根据请求月份的本月-日返回一个 MonthDay
下面的程序说明了 with() 方法:
方案一:
// 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
方案二:
// 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: Java Java.time.Month)