Java Instant minus()方法及示例

Java Instant minus()方法及示例

在Instant类中,根据传递给它的参数,有两种类型的minus()方法。

minus(long amountTosubtract, TemporalUnit unit)

Instant 类的 minus() 方法用于返回一个减去指定单位数量的瞬间副本。如果由于单位不被支持或其他原因而无法减去该数量,则会抛出一个异常。

语法:

public Instant minus(long amountToSubtract,
                     TemporalUnit unit)

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

  • amountToSubtract ,是要减去结果的单位数量,可以是负数,以及
  • unit ,是要减去的金额的单位,不是空的。

返回值: 该方法返回基于此瞬时的减去指定数量的 Instant

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

  • DateTimeException – 如果不能做减法。
  • UnsupportedTemporalTypeException – 如果单位不被支持。
  • ArithmeticException – 如果发生数字溢出。

下面的程序说明了minus()方法:

程序1:

// Java program to demonstrate
// Instant.minus() method
 
import java.time.*;
import java.time.temporal.ChronoUnit;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create an Instant object
        Instant instant
            = Instant.parse("2018-12-30T19:34:50.63Z");
 
        // subtract 20 DAYS to Instant
        Instant value
            = instant.minus(20, ChronoUnit.DAYS);
 
        // print result
        System.out.println("Instant after subtracting DAYS: "
                           + value);
    }
}

输出

Instant after subtracting DAYS: 2018-12-10T19:34:50.630Z

minus(TemporalAmount amountTosubtract)

即时 类的 minus() 方法用于返回该即时类的副本,并将指定的金额减去日期时间。该金额通常是Period或Duration,但也可以是任何其他实现TemporalAmount接口的类型。

语法:

public Instant minus(TemporalAmount amountTosubtract)

参数: 该方法接受一个单参数 amountTosubtract ,它是要减去的金额,它不应该是空的。

返回值: 该方法返回基于该日期时间的 即时 减法,而不是空的。

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

  • DateTimeException – 如果不能做减法。
  • ArithmeticException – 如果发生数字溢出。

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

程序1:

// Java program to demonstrate
// Instant.minus() method
 
import java.time.*;
public class GFG {
    public static void main(String[] args)
    {
 
        // create an Instant object
        Instant inst
            = Instant.parse("2018-12-30T19:34:50.63Z");
 
        // subtract 10 Days to Instant
        Instant value
            = inst.minus(Period.ofDays(10));
 
        // print result
        System.out.println("Instant after subtracting Days: "
                           + value);
    }
}

输出

Instant after subtracting Days: 2018-12-20T19:34:50.630Z

参考文献:

https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minus(java.time.temporal.TemporalAmount)
https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minus(long, java.time.temporalUnit)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程