Java中的 Duration withSeconds(long) 方法和示例
Java.time 包中Duration 类的withSeconds(long)方法用于获取此持续时间的不可变副本,其中指定的秒数作为参数传递。
句法:
public Duration withSeconds(long amountOfSeconds)
参数:此方法接受参数amountOfSeconds ,它是秒数。
返回值:此方法返回作为参数传递的秒的持续时间。
下面的示例说明了 Duration.withSeconds() 方法:
示例 1:
// Java code to illustrate withSeconds() method
import java.time.Duration;
public class GFG {
public static void main(String[] args)
{
// Get the amount of seconds
long amountOfSeconds = 300;
// Duration using parse() method
Duration duration
= Duration.parse("P2DT3H4M");
// Get the duration in seconds
// using withSeconds() method
System.out.println(duration
.withSeconds(amountOfSeconds));
}
}
输出:
PT5M
示例 2:
// Java code to illustrate withSeconds() method
import java.time.Duration;
public class GFG {
public static void main(String[] args)
{
// Get the amount of seconds
long amountOfSeconds = 3000;
// Duration using ofHours() method
Duration duration
= Duration.ofHours(5);
// Get the duration in seconds
// using withSeconds() method
System.out.println(duration
.withSeconds(amountOfSeconds));
}
}
输出:
PT50M
参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/Duration.html#withSeconds-long-