Java中的LocalDate withYear()方法
使用withYear()Java中LocalDate类中的方法,可以完成按需更改年份的LocalDate的不可变副本。此方法需要一个参数,即要在LocalDate中设置的年份,并且它返回LocalDate并根据需要更改年份。
演示此的程序如下所示-
示例
import java.time.*;
public class Main {
public static void main(String[] args) {
LocalDate ld1 = LocalDate.parse("2019-02-15");
System.out.println("The LocalDate is: " + ld1);
LocalDate ld2 = ld1.withYear(2015);
System.out.println("The LocalDate with year altered is: " + ld2);
}
}输出结果
The LocalDate is: 2019-02-15 The LocalDate with year altered is: 2015-02-15
现在让我们了解上面的程序。
首先显示LocalDate。然后使用方法显示年份更改为2015的LocalDatewithYear()。演示这的代码片段如下-
LocalDate ld1 = LocalDate.parse("2019-02-15");
System.out.println("The LocalDate is: " + ld1);
LocalDate ld2 = ld1.withYear(2015);
System.out.println("The LocalDate with year altered is: " + ld2);