Java ZonedDateTime until()方法及示例
ZonedDateTime 类的until () 方法用于使用TemporalUnit计算两个ZonedDateTime对象之间的时间量。起点和终点是this和作为参数传递的指定ZonedDateTime。如果终点在起点之前,结果将是负数。该计算返回一个整数,代表两个ZonedDateTime之间的完整单位数。这个实例是不可改变的,不受这个方法调用的影响。
语法
public long until(Temporal endExclusive, TemporalUnit unit)
参数: 该方法接受两个参数endExclusive,它是结束日期,exclusive,它被转换为一个ZonedDateTime,单位是测量数量的单位。
返回值: 该方法返回这个ZonedDateTime和结束ZonedDateTime之间的时间量。
异常: 该方法会抛出以下异常。
- DateTimeException – 如果不能计算金额,或者结束的时间性不能转换为ZonedDateTime。
- UnsupportedTemporalTypeException – 如果单位不被支持。
- ArithmeticException – 如果发生数字溢出。
下面的程序说明了until()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.until() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create ZonedDateTime objects
ZonedDateTime z1
= ZonedDateTime
.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
ZonedDateTime z2
= ZonedDateTime
.parse("2018-10-25T23:12:31.123+02:00[Europe/Paris]");
// apply until method of ZonedDateTime class
long result
= z1.until(z2,
ChronoUnit.HOURS);
// print results
System.out.println("Result in HOURS: "
+ result);
}
}
输出。
Result in HOURS: -1000
程序2
// Java program to demonstrate
// ZonedDateTime.until() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create ZonedDateTime objects
ZonedDateTime z1
= ZonedDateTime
.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
ZonedDateTime z2
= ZonedDateTime
.parse("2018-10-25T23:12:31.123+02:00[Europe/Paris]");
// applynedDateTime.parseZonedDateTime class
long result
= z2.until(z1,
ChronoUnit.DAYS);
// print results
System.out.println("Result in DAYS: "
+ result);
}
}
输出。
Result in DAYS: 41
参考资料:
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#until(java.time.temporal.Temporal, java.time.temporalUnit)