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


Java LocalDate withMonth()用法及代码示例


Java中LocalDate类的withMonth()方法返回已更改month-of-year的此LocalDate的副本。

用法:

public LocalDate withMonth(int month)

参数:此方法接受一个强制性参数月,该月指定要在结果中设置的month-of-year,范围从1月1日到12月12日。


返回值:该函数基于此日期和所请求的月份返回LocalDate,而不是null。

异常:当month-of-year值无效时,该函数引发DateTimeException。

以下示例程序旨在说明LocalDate.withMonth()方法:

示例1:

// Program to illustrate the withMonth() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
  
        // Parses the date 
        LocalDate dt1 = LocalDate.parse("2018-12-07"); 
        LocalDate result = dt1.withMonth(01); 
  
        // Prints the date with year 
        System.out.println("The date with month is: " + result); 
    } 
}
输出:
The date with month is: 2018-01-07

示例2:

// Program to illustrate the withMonth() method 
// Exceptions 
import java.util.*; 
import java.time.*; 
import java.time.temporal.ChronoField; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
  
        try { 
            // Parses the date 
            LocalDate dt1 = LocalDate.parse("2018-12-07"); 
            LocalDate result = dt1.withMonth(13); 
  
            // Prints the date with year 
            System.out.println("The date with month is: " + result); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
输出:
java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 13

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



相关用法


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