當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。