LocalDateTime类的until()方法用于使用TemporalUnit计算两个LocalDateTime对象之间的时间量。起点和终点是此点,指定的LocalDateTime作为参数传递。如果结束在开始之前,结果将为负。计算返回一个整数,代表两个LocalDateTime之间的完整单位数。此实例是不可变的,不受此方法调用的影响。
用法:
public long until(Temporal endExclusive, TemporalUnit unit)
参数:此方法接受两个参数endExclusive,它是结束日期,exclusive,它转换为LocalDateTime,单位是测量数量的单位。
返回值:此方法返回此LocalDateTime与结束LocalDateTime之间的时间量。
异常:此方法引发以下异常:
DateTimeException-如果无法计算数量,或者结束时态不能转换为LocalDateTime。
UnsupportedTemporalTypeException-如果不支持该单元。
ArithmeticException-如果发生数字溢出。
以下示例程序旨在说明until()方法:
示例1:
// Java program to demonstrate
// LocalDateTime.until() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create LocalDateTime objects
LocalDateTime l1
= LocalDateTime
.parse("2018-12-06T19:21:12");
LocalDateTime l2
= LocalDateTime
.parse("2018-10-25T23:12:31.123");
// apply until method of LocalDateTime class
long result
= l2.until(l1,
ChronoUnit.MINUTES);
// print results
System.out.println("Result in MINUTES: "
+ result);
}
}
输出:
Result in MINUTES: 60248
示例2:
// Java program to demonstrate
// LocalDateTime.until() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create LocalDateTime objects
LocalDateTime l1
= LocalDateTime
.parse("2018-12-06T19:21:12");
LocalDateTime l2
= LocalDateTime
.parse("2018-10-25T23:12:31.123");
// applynedDateTime.parseLocalDateTime class
long result
= l2.until(l1,
ChronoUnit.MONTHS);
// print results
System.out.println("Result in MONTHS: "
+ result);
}
}
输出:
Result in MONTHS: 1