Java Duration getUnits()方法及示例
java.time包中Duration类的getUnits()方法用于获取该期限所支持的单位列表。
语法。
public List<TemporalUnit> getUnits()
参数。此方法不接受任何参数。
返回值。该方法返回该期限所支持的单位的列表。这些单位是SECONDS和NANOS。
下面的例子说明了Duration.getUnits()方法。
例1:
// Java code to illustrate getUnits() method
import java.time.Duration;
import java.time.temporal.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Get the text
String time = "P2DT3H4M";
// Duration using parse() method
Duration duration
= Duration.parse(time);
// Duration using getUnits() method
List<TemporalUnit>
listOfUnits = duration.getUnits();
System.out.println("List of Units: "
+ listOfUnits);
}
}
输出:
List of Units: [Seconds, Nanos]
例2:
// Java code to illustrate getUnits() method
import java.time.Duration;
import java.time.temporal.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Get the text
String time = "P1DT4M";
// Duration using parse() method
Duration duration
= Duration.parse(time);
// Duration using getUnits() method
List<TemporalUnit>
listOfUnits = duration.getUnits();
System.out.println("List of Units: "
+ listOfUnits);
}
}
输出:
List of Units: [Seconds, Nanos]
参考资料: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#getUnits-