Java中的LocalDateTime withSecond()方法
使用withSecond()Java中LocalDateTime类中的方法,可以完成LocalDateTime的不可变副本,并根据需要更改秒数。此方法需要一个参数,即要在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.withSecond(45);
System.out.println("The LocalDateTime with seconds altered is: " + ldt2);
}
}输出结果
The LocalDateTime is: 2019-02-18T23:15:30 The LocalDateTime with seconds altered is: 2019-02-18T23:15:45
现在让我们了解上面的程序。
首先显示LocalDateTime。然后使用方法显示将秒更改为45的LocalDateTimewithSecond()。演示这的代码片段如下-
LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
System.out.println("The LocalDateTime is: " + ldt1);
LocalDateTime ldt2 = ldt1.withSecond(45);
System.out.println("The LocalDateTime with seconds altered is: " + ldt2);