当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java MonthDay with()用法及代码示例


MonthDay类的with(Month month)方法用于使用传递的month来更改MonthDay对象的month-of-year,然后在该方法之后返回更改后的MonthDay的副本。如果day-of-month值在更改操作后的指定月份内无效,则日期将调整为最后一个有效的day-of-month。

用法:

public MonthDay with(Month month)

参数:此方法接受月份作为参数,该参数是要在返回的month-day中设置的month-of-year。


返回值:此方法返回基于此month-day的MonthDay以及所请求的月份

以下示例程序旨在说明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)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 MonthDay with() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。