Java中LocalDate類的withDayOfMonth()方法返回已更改day-of-month的此LocalDate的副本。
用法:
public LocalDate withDayOfMonth(int dayOfMonth)
參數:此方法接受強製性參數dayOfMonth,其中day-of-month可以在1到28-31之間設置結果。
返回值:該函數基於此日期和所請求的日期返回LocalDate,而不是null。
異常:當月份中的日期值無效時,該函數將引發DateTimeException。
以下示例程序旨在說明LocalDate.withDayOfMonth()方法:
示例1:
// Program to illustrate the withDayOfMonth() 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.withDayOfMonth(01);
// Prints the date with year
System.out.println("The date with day of the month is: " + result);
}
}
輸出:
The date with day of the month is: 2018-12-01
示例2:
// Program to illustrate the withDayOfMonth() 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.withDayOfMonth(35);
// Prints the date with year
System.out.println("The date with day of the month is: " + result);
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 35
參考: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#withDayOfMonth(int)
相關用法
- Java ZonedDateTime withDayOfMonth()用法及代碼示例
- Java OffsetDateTime withDayOfMonth()用法及代碼示例
- Java LocalDateTime withDayOfMonth()用法及代碼示例
- Java MonthDay withDayOfMonth()用法及代碼示例
- Java LocalDate now()用法及代碼示例
- Java LocalDate get()用法及代碼示例
- Java LocalDate plus()用法及代碼示例
- Java LocalDate with()用法及代碼示例
- Java LocalDate now()用法及代碼示例
- Java LocalDate plusWeeks()用法及代碼示例
- Java LocalDate hashCode()用法及代碼示例
- Java LocalDate isAfter()用法及代碼示例
- Java LocalDate isBefore()用法及代碼示例
- Java LocalDate getMonthValue()用法及代碼示例
- Java LocalDate getYear()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 LocalDate withDayOfMonth() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。