Java中的即时adjustInto()方法与示例
Instant 类的adjustInto(Temporal temporal)方法调整传递的时间对象,使其具有应用此方法的瞬间。
句法:
public Temporal adjustInto(Temporal temporal)
参数:此方法接受一个参数temporal ,该参数是要调整的目标时间对象。它不应该为空。
返回值:此方法返回调整后的时间对象。
异常:此方法抛出以下异常:
- 如果此方法无法进行调整,则DateTimeException 。
- 如果在调整时发生数值溢出,则会出现ArithmeticException 。
下面的程序说明了 Instant.adjustInto() 方法:
方案一:
// 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
方案二:
// 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: Java Java.time.temporal.Temporal)