Java Duration withSeconds(long)方法及示例
java.time包中Duration类的withSeconds(long)方法用于获取该持续时间的不可变副本,并将指定的秒数作为参数传递。
语法。
public Duration withSeconds(long amountOfSeconds)
参数。该方法接受一个参数 amountOfSeconds,它是秒数的数量。
返回值。该方法返回一个以参数形式传递的秒数的Duration。
下面的例子说明了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-