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)
相關用法
- Java ZonedDateTime withMonth()用法及代碼示例
- Java OffsetDateTime withMonth()用法及代碼示例
- Java LocalDateTime withMonth()用法及代碼示例
- Java YearMonth withMonth()用法及代碼示例
- Java MonthDay withMonth()用法及代碼示例
- Java LocalDate now()用法及代碼示例
- Java LocalDate plus()用法及代碼示例
- Java LocalDate get()用法及代碼示例
- Java LocalDate with()用法及代碼示例
- Java LocalDate now()用法及代碼示例
- Java LocalDate isBefore()用法及代碼示例
- Java LocalDate isAfter()用法及代碼示例
- Java LocalDate getMonthValue()用法及代碼示例
- Java LocalDate getYear()用法及代碼示例
- Java LocalDate isEqual()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 LocalDate withMonth() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。