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


Java OffsetDateTime withMonth()用法及代碼示例


Java中OffsetDateTime類的withMonth()方法返回此OffsetDateTime的副本,其中month-of-year如參數中所述進行了更改。

用法:

public OffsetDateTime withMonth(int month)

參數:此方法接受一個參數月,該月指定要在結果中設置的month-of-year,範圍從1到12。


返回值:它基於此日期返回一個OffsetDateTime,並帶有請求的month-of-year,並且不為null。

異常:當month-of-year值無效時,程序將引發DateTimeException。

以下示例程序旨在說明withMonth()方法:

示例1:

// Java program to demonstrate the withMonth() method 
  
import java.time.OffsetDateTime; 
import java.time.ZonedDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Parses the date1 
        OffsetDateTime date1 
            = OffsetDateTime 
                  .parse( 
                      "2018-12-12T13:30:30+05:00"); 
  
        // Prints dates 
        System.out.println("Date1: " + date1); 
  
        // Changes the month-of-year 
        System.out.println("Date1 after altering month-of-year: "
                           + date1.withMonth(10)); 
    } 
}
輸出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering month-of-year: 2018-10-12T13:30:30+05:00

示例2:

// Java program to demonstrate the withMonth() method 
  
import java.time.OffsetDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        try { 
            // Parses the date1 
            OffsetDateTime date1 
                = OffsetDateTime 
                      .parse( 
                          "2018-12-12T13:30:30+05:00"); 
  
            // Prints dates 
            System.out.println("Date1: " + date1); 
  
            // Changes the minute of day 
            System.out.println("Date1 after altering month-of-year: "
                               + date1.withMonth(27)); 
        } 
        catch (Exception e) { 
            System.out.println("Exception: " + e); 
        } 
    } 
}
輸出:
Date1: 2018-12-12T13:30:30+05:00
Exception: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 27

參考: https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#withMonth(int)



相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 OffsetDateTime withMonth() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。