Java 中 LocalDateTime 的 withYear() 方法


在 Java 中的 LocalDateTime 类的 withYear() 方法用于设置一个不可变副本,其中更改了所需的年。该方法需要一个参数,即在 LocalDateTime 中要设置的年,并返回所需的年已更改的 LocalDateTime。

一个演示此内容的程序如下所示 -

示例

 在线演示

import java.time.*;
public class Main {
   public static void main(String[] args) {
      LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
      System.out.println("The LocalDateTime is: " + ldt1);
      LocalDateTime ldt2 = ldt1.withYear(2020);
      System.out.println("The LocalDateTime with year altered is: " + ldt2);
   }
}

输出

The LocalDateTime is: 2019-02-18T23:15:30
The LocalDateTime with year altered is: 2020-02-18T23:15:30

现在让我们了解一下上面的程序。

首先显示 LocalDateTime。然后使用 withYear() 方法将 LocalDateTime 的年更改为 2020 年并显示。一个演示此内容的代码片段如下所示 -

LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
System.out.println("The LocalDateTime is: " + ldt1);
LocalDateTime ldt2 = ldt1.withYear(2020);
System.out.println("The LocalDateTime with year altered is: " + ldt2);

更新于: 2019-07-30

101 视图

启动您的职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.