Java中的 OffsetTime adjustInto() 方法及示例
Java中 OffsetDateTime 类的adjustInto()方法将指定的时间对象调整为与该对象具有相同的时间。
句法 :
public Temporal adjustInto(Temporal temporal)
参数:此方法接受单个参数temporal ,它指定要调整的目标对象,而不是 null。
返回值:返回调整后的对象,不为空
错误和异常:此方法抛出两个异常,如下所述:
- DateTimeException : 如果无法进行调整。
- ArithmeticException : 如果发生数值溢出。
下面的程序说明了 adjustInto() 方法:
程序 1:
// Java program to demonstrate the adjustInto() method
import java.time.OffsetTime;
import java.time.ZonedDateTime;
public class GFG {
public static void main(String[] args)
{
// Current time
ZonedDateTime date = ZonedDateTime.now();
// Prints the current time
System.out.println("Current date:" + date);
// Parsed the date
OffsetTime date1 = OffsetTime.parse("14:30:30+05:00");
// Adjusts
date = (ZonedDateTime)date1.adjustInto(date);
System.out.println("Adjusted date:" + date);
}
}
输出:
Current date:2018-12-11T10:01:37.877Z[Etc/UTC]
Adjusted date:2018-12-11T14:30:30Z[Etc/UTC]
方案二:
// Java program to demonstrate the adjustInto()
// method exceptions
import java.time.OffsetTime;
import java.time.ZonedDateTime;
public class GFG {
public static void main(String[] args)
{
try {
// Current time
// Current time
ZonedDateTime date = ZonedDateTime.now();
// Prints the current time
System.out.println("Current date:" + date);
// Parsed the date
OffsetTime date1 = OffsetTime.parse("25:30:30+05:00");
// Adjusts
date = (ZonedDateTime)date1.adjustInto(date);
System.out.println("Adjusted date:" + date);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Current date:2018-12-11T10:01:42.520Z[Etc/UTC]
java.time.format.DateTimeParseException: Text '25:30:30+05:00' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 25
参考:https: Java/time/OffsetTime.html#adjustInto-java.time.temporal.Temporal-