当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Duration ofSeconds(long, long)用法及代码示例


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

用法:

public static Duration ofSeconds(long seconds, long nanoAdjustment)

参数:此方法接受两个参数:


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

返回值:此方法返回以1秒格式表示时间的Duration。

异常:如果输入的秒数超过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-



相关用法


注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Duration ofSeconds(long, long) method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。