YearMonth類的withYear(int year)方法用於使用傳遞的Year來更改YearMonth對象的年份,此方法之後將返回更改後的YearMonth的副本。此實例是不可變的,不受此方法調用的影響。
用法:
public YearMonth withYear(int year)
參數:此方法接受月份作為參數,該年份是在從MIN_YEAR到MAX_YEAR的返回year-month中設置的年份。
返回值:此方法基於此year-month和所請求的年份返回YearMonth。
異常:如果年份值無效,則此方法引發DateTimeException。
以下示例程序旨在說明withYear()方法:
示例1:
// Java program to demonstrate
// YearMonth.withYear() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a YearMonth object
YearMonth yr
= YearMonth.of(2019, 12);
// print instance
System.out.println("YearMonth before"
+ " applying method: "
+ yr);
// apply withYear method of YearMonth class
YearMonth updatedlocal = yr.withYear(2023);
// print instance
System.out.println("YearMonth after"
+ " applying method: "
+ updatedlocal);
}
}
輸出:
YearMonth before applying method: 2019-12 YearMonth after applying method: 2023-12
示例2:
// Java program to demonstrate
// YearMonth.withYear() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a YearMonth object
YearMonth yr
= YearMonth.of(2022, 7);
// print instance
System.out.println("YearMonth before"
+ " applying method: "
+ yr);
// apply withYear method of YearMonth class
YearMonth updatedlocal = yr.withYear(1992);
// print instance
System.out.println("YearMonth after"
+ " applying method: "
+ updatedlocal);
}
}
輸出:
YearMonth before applying method: 2022-07 YearMonth after applying method: 1992-07
參考文獻: https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#withYear(int)
相關用法
- Java ZonedDateTime withYear()用法及代碼示例
- Java LocalDate withYear()用法及代碼示例
- Java OffsetDateTime withYear()用法及代碼示例
- Java LocalDateTime withYear()用法及代碼示例
- Java YearMonth until()用法及代碼示例
- Java YearMonth with()用法及代碼示例
- Java YearMonth isAfter()用法及代碼示例
- Java YearMonth withMonth()用法及代碼示例
- Java YearMonth isBefore()用法及代碼示例
- Java YearMonth isLeapYear()用法及代碼示例
- Java YearMonth isValidDay()用法及代碼示例
- Java YearMonth lengthOfYear()用法及代碼示例
- Java YearMonth query()用法及代碼示例
- Java YearMonth range()用法及代碼示例
- Java YearMonth plus(TemporalAmount)用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 YearMonth withYear() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。