Java Instant until()方法及实例

Java Instant until()方法及实例

Instant 类的until () 方法用于使用TemporalUnit计算两个Instant对象之间的时间量。起点和终点是this和作为参数传递的指定即时。如果结束点在开始点之前,结果将是负数。计算返回一个整数,代表两个Instant之间的完整单位的数量。这个实例是不可改变的,不受这个方法调用的影响。

语法

public long until(Temporal endExclusive, TemporalUnit unit)

参数: 该方法接受两个参数 endExclusive ,它是结束日期;exclusive,它被转换为Instant; unit ,它是测量金额的单位。

返回值: 该方法返回这个Instant和结束Instant之间的时间量。

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

  • DateTimeException – 如果不能计算数量,或者不能将结束时间转换为瞬时。
  • UnsupportedTemporalTypeException – 如果单位不被支持。
  • ArithmeticException – 如果发生数字溢出。

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

程序1 :

// Java program to demonstrate
// Instant.until() method
  
import java.time.*;
import java.time.temporal.ChronoUnit;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create Instant objects
        Instant instant1
            = Instant.parse("2019-01-03T19:35:50.00Z");
        Instant instant2
            = Instant.parse("2019-01-04T13:18:59.00Z");
  
        // apply until method of Instant class
        long result
            = instant1.until(instant2,
                             ChronoUnit.MINUTES);
  
        // print results
        System.out.println("Result in Minutes: "
                           + result);
    }
}

输出:

Result in Minutes: 1063

程序2

// Java program to demonstrate
// Instant.until() method
  
import java.time.*;
import java.time.temporal.ChronoUnit;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create Instant objects
        Instant instant1
            = Instant.parse("2010-01-03T19:35:50.00Z");
        Instant instant2
            = Instant.parse("2019-01-04T13:18:59.00Z");
  
        // apply until method of Instant class
        long result
            = instant1.until(instant2,
                             ChronoUnit.DAYS);
  
        // print results
        System.out.println("Result in DAYS: "
                           + result);
    }
}

输出:

Result in DAYS: 3287

参考资料:
https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#until(java.time.temporal.Temporal, java.time.temporalUnit)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程