Java Instant minusNanos()方法及示例

Java Instant minusNanos()方法及示例

Instant类minusNanos() 方法将作为参数的纳秒值从这个瞬间中减去,并将结果作为一个瞬间对象返回。这个返回的 Instant 是不可改变的。

语法:

public Instant minusNanos(long nanosToSubtract)

参数: 该方法接受一个参数 nanosToSubtract ,即要减去的纳秒数。

返回: 该方法返回减去纳秒数后的 Instant

异常: 该方法抛出以下异常:

  • DateTimeException :如果结果超过了最大或最小的瞬间。
  • ArithmeticException :如果发生数字溢出。

以下程序说明了minusNanos()方法:

程序1:

// Java program to demonstrate
// Instant.minusNanos() method
 
import java.time.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a Instant object
        Instant instant
            = Instant.parse("2018-12-30T19:34:50.63Z");
 
        // current Instant
        System.out.println("Initialize instant: "
                           + instant);
 
        // subtract 430000000 nanoseconds
        // means .43 seconds from this instant
        Instant returnedValue
            = instant.minusNanos(430000000);
 
        // print result
        System.out.println("Returned Instant: "
                           + returnedValue);
    }
}

输出

Initialize instant: 2018-12-30T19:34:50.630Z
Returned Instant: 2018-12-30T19:34:50.200Z

程序2:

// Java program to demonstrate
// Instant.minusNanos() method
 
import java.time.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a Instant object
        Instant instant = Instant.now();
 
        // current Instant
        System.out.println("Current instant: "
                           + instant);
 
        // subtract 540000000 nanoseconds
        // means .564 seconds from this instant
        Instant returnedValue
            = instant.minusNanos(540000000);
 
        // print result
        System.out.println("Returned Instant: "
                           + returnedValue);
    }
}

输出

Current instant: 2018-11-27T06:43:58.495Z
Returned Instant: 2018-11-27T06:43:57.955Z

参考文献: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minusNanos(long)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程