Java中的 LocalTime withSecond() 方法及示例
LocalTime类的withSecond()方法用于获取此 LocalTime 的副本,其中秒数更改为作为参数传递给此方法的秒数。此 LocalTime 的其余值将保持不变。此实例是不可变的,不受此方法调用的影响。
句法:
public LocalTime withSecond(int second)
参数:此方法接受单个参数second ,它表示要在结果中设置的秒数,从 0 到 59。
返回值:该方法根据这个时间和请求的秒数返回一个LocalTime 实例。
异常:如果第二个值无效,此方法会抛出异常DateTimeException
下面的程序说明了 withSecond() 方法:
方案一:
// Java program to demonstrate
// LocalTime.withSecond() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a LocalTime object
LocalTime time
= LocalTime.parse("19:34:50.63");
// print time
System.out.println("Old LocalTime: "
+ time);
// Get a new LocalDateTime with seconds 4
LocalTime newtime = time.withSecond(4);
// print result
System.out.println("New LocalDateTime: "
+ newtime);
}
}
输出:
Old LocalTime: 19:34:50.630
New LocalDateTime: 19:34:04.630
方案二:
// Java program to demonstrate
// LocalTime.withSecond() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a LocalTime object
LocalTime time
= LocalTime.parse("01:21:30.13");
// print time
System.out.println("Old LocalTime: "
+ time);
// Get a new LocalDateTime with seconds 23
LocalTime newtime = time.withSecond(23);
// print result
System.out.println("New LocalDateTime: "
+ newtime);
}
}
输出:
Old LocalTime: 01:21:30.130
New LocalDateTime: 01:21:23.130
参考资料: https: Java/time/LocalTime.html#withSecond(int)