📌  相关文章
📜  Java中的 Instant minusNanos() 方法和示例

📅  最后修改于: 2022-05-13 01:54:27.732000             🧑  作者: Mango

Java中的 Instant minusNanos() 方法和示例

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

public Instant minusNanos(long nanosToSubtract)

参数:此方法接受一个参数nanosToSubtract ,它是要减去的纳秒。
返回:此方法在减去纳秒后返回Instant
异常:此方法抛出以下异常:

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

下面的程序说明了 minusNanos() 方法:
方案一:

Java
// 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);
    }
}


Java
// 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);
    }
}


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

方案二:

Java

// 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: Java/time/Instant.html#minusNanos(long)