📜  Java中的即时减秒()方法与示例

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

Java中的即时减秒()方法与示例

Instant 类minusSeconds()方法从该瞬间中减去指定的秒值,并将结果作为瞬间对象返回。这个瞬间是不变的。
句法:

public Instant minusSeconds(long secondsToSubtract)

参数:此方法接受一个参数secondsToSubtract ,即要减去的秒数。
返回:此方法在减去秒数后返回Instant

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

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

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

Java
// Java program to demonstrate
// Instant.minusSeconds() method
 
import java.time.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a Instant object
        Instant instant
            = Instant.parse("2018-10-30T09:05:55.13Z");
 
        // current Instant
        System.out.println("Initialize instant: "
                           + instant);
 
        // subtract 4300 seconds from this instant
        Instant returnedValue
            = instant.minusSeconds(4300);
 
        // print result
        System.out.println("Returned Instant: "
                           + returnedValue);
    }
}


Java
// Java program to demonstrate
// Instant.minusSeconds() 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 54000 from this instant
        Instant returnedValue
            = instant.minusSeconds(54000);
 
        // print result
        System.out.println("Returned Instant: "
                           + returnedValue);
    }
}


输出
Initialize instant: 2018-10-30T09:05:55.130Z
Returned Instant: 2018-10-30T07:54:15.130Z

方案二:

Java

// Java program to demonstrate
// Instant.minusSeconds() 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 54000 from this instant
        Instant returnedValue
            = instant.minusSeconds(54000);
 
        // print result
        System.out.println("Returned Instant: "
                           + returnedValue);
    }
}
输出:
Current instant: 2018-11-27T06:44:04.901Z
Returned Instant: 2018-11-26T15:44:04.901Z

参考资料:https: Java/time/Instant.html#minusSeconds(long)