Java Duration get(TemporalUnit)方法及示例

来源:这里教程网 时间:2026-02-17 20:50:06 作者:

Java Duration get(TemporalUnit)方法及示例

java.time包中Duration类的get(TemporalUnit)方法用于获取作为参数的单位的值。这个方法只支持SECONDS和NANOS这两个单位,其他的都会出现异常。

语法。

public long get(TemporalUnit unit)

参数。这个方法接受一个参数单位,它是要取值的TemporalUnit。

返回值。该方法返回一个作为参数传递的单位的长值。

异常情况。这个方法会抛出。

DateTimeException : 如果单位不被支持。UnsupportedTemporalTypeException:如果单位不被支持。

下面的例子说明了Duration.get()方法。

例子1:

// Java code to illustrate get() method  import java.time.Duration;import java.time.temporal.*;  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 get() method        long getSeconds            = duration.get(ChronoUnit.SECONDS);          System.out.println("Seconds: "                           + getSeconds);          // Duration using get() method        long getNanos            = duration.get(ChronoUnit.NANOS);          System.out.println("Nanos: "                           + getNanos);    }}

输出:

Seconds: 183840Nanos: 0

例2:

// Java code to illustrate get() method  import java.time.Duration;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // Get the text        String time = "P2DT3H4M";          // Duration using parse() method        Duration duration            = Duration.parse(time);          try {            // Duration using get() method            long getMinutes                = duration.get(ChronoUnit.MINUTES);        }        catch (Exception e) {            System.out.println("Exception: " + e);        }    }}

输出:

Exception: java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Minutes

参考资料。甲骨文文件

相关推荐