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


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。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。