Java Instant adjustInto()方法与实例
Instant类的 adjustInto(Temporal temporal) 方法将传递的时间对象调整为具有该方法所适用的瞬间。
语法
public Temporal adjustInto(Temporal temporal)
参数: 该方法接受一个参数 temporal ,它是要调整的目标时间对象。它不应该是空的。
返回值 :该方法返回调整后的时间对象。
异常: 该方法抛出以下异常。
- DateTimeException 如果这个方法不能进行调整。
- 如果调整时发生数字溢出,则抛出 ArithmeticException 。
下面的程序说明了Instant.adjustInto()方法。
程序1 :
// Java program to demonstrate
// Instant.adjustInto() method
import java.time.*;
import java.time.temporal.Temporal;
public class GFG {
public static void main(String[] args)
{
// create an instance object
Instant instant
= Instant.parse("2018-11-20T16:55:30.00Z");
// create a Temporal object
// which is equal to OffsetDateTime object
OffsetDateTime passTemporal
= OffsetDateTime.now();
// print passed Value
System.out.println("Passed Value: "
+ passTemporal);
// apply adjustInto method
// to adjust OffsetDateTime Temporal
// to instant object
Temporal returnTemporal
= instant.adjustInto(passTemporal);
// print results
System.out.println("Returned Value: "
+ (OffsetDateTime)returnTemporal);
}
}
输出:
Passed Value: 2018-11-22T09:22:17.297Z
Returned Value: 2018-11-20T16:55:30Z
程序2
// Java program to demonstrate
// Instant.adjustInto() method
import java.time.*;
import java.time.temporal.Temporal;
public class GFG {
public static void main(String[] args)
{
// create an instance object
Instant instant
= Instant.parse("2018-11-17T06:50:39.00Z");
// create a Temporal object
// which is equal to ZonedDateTime object
ZonedDateTime passTemporal
= ZonedDateTime.now();
// print passed Value
System.out.println("Passed Value: "
+ passTemporal);
// apply adjustInto method
// to adjust ZonedDateTime Temporal
// to instant object
Temporal returnTemporal
= instant.adjustInto(passTemporal);
// print results
System.out.println("Returned Value: "
+ (ZonedDateTime)returnTemporal);
}
}
输出:
Passed Value: 2018-11-22T09:22:20.995Z[Etc/UTC]
Returned Value: 2018-11-17T06:50:39Z[Etc/UTC]
程序3 。
// Java program to demonstrate
// Instant.adjustInto() method
import java.time.*;
import java.time.temporal.Temporal;
public class GFG {
public static void main(String[] args)
{
// create an instance object
Instant instant
= Instant.parse("2017-11-01T16:25:00.00Z");
// create a Temporal object
// which is equal to Instant object
// with current Instant
Temporal passTemporal
= Instant.now();
// print passed Value
System.out.println("Passed Value: "
+ passTemporal);
// apply adjustInto method to adjust Temporal
// to this instant object
Temporal returnTemporal
= instant.adjustInto(passTemporal);
// print results
System.out.println("Returned Value: "
+ returnTemporal);
}
}
输出:
Passed Value: 2018-11-22T09:22:23.298Z
Returned Value: 2017-11-01T16:25:00Z
参考资料: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#adjustInto(java.time.temporal.Temporal)。