Java Duration ofSeconds(long, long)方法及示例

Java Duration ofSeconds(long, long)方法及示例

java.time包中Duration类的ofSeconds(long, long)方法是用来获取1秒格式的持续时间。在这个方法中,秒数被计算为1秒格式的总秒数,即每秒钟1秒。第二个参数nanoAdjustment用于调整纳秒单位的秒数。

语法。

public static Duration ofSeconds(long seconds, long nanoAdjustment)

参数。这个方法接受两个参数。

  • seconds : 是秒数。它可以是正数或负数。
  • nanoAdjustment : 是要在秒内进行的调整。

返回值。该方法返回一个持续时间,代表1秒格式的时间。

异常情况。如果输入的秒数超过了Duration的容量,该方法会抛出ArithmeticException。

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

例子1:

// Java code to illustrate ofSeconds() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // input number of Seconds
        long noOfSeconds = 214545;
  
        // input nanoSeconds adjustment to be made
        long nanoSecAdjust = 10000;
  
        // Duration using ofSeconds() method
        Duration duration
            = Duration.ofSeconds(noOfSeconds);
        Duration duration1
            = Duration.ofSeconds(noOfSeconds,
                                 nanoSecAdjust);
  
        System.out.println("Duration without adjustment: "
                           + duration.getSeconds());
        System.out.println("Duration with adjustment: "
                           + duration1.getSeconds());
    }
}

输出:

Duration without adjustment: 214545
Duration with adjustment: 214545

例2:

// Java code to illustrate ofSeconds() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // input number of Seconds
        long noOfSeconds = 214545;
  
        // input nanoSeconds adjustment to be made
        long nanoSecAdjust = -10000;
  
        // Duration using ofSeconds() method
        Duration duration
            = Duration.ofSeconds(noOfSeconds);
        Duration duration1
            = Duration.ofSeconds(noOfSeconds,
                                 nanoSecAdjust);
  
        System.out.println("Duration without adjustment: "
                           + duration.getSeconds());
        System.out.println("Duration with adjustment: "
                           + duration1.getSeconds());
    }
}

输出:

Duration without adjustment: 214545
Duration with adjustment: 214544

参考资料: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofSeconds-long-long-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Java Duration