Java OffsetDateTime adjustInto()方法及示例
Java中OffsetDateTime类的 adjustInto() 方法将指定的时间对象调整为与此对象相同的日期和时间。
语法:
public Temporal adjustInto(Temporal temporal)
参数: 该方法接受一个 临时 参数,指定要调整的目标对象,不为空。
返回值 :它返回调整后的对象,而不是空的。
错误和异常: 该方法抛出两个异常,如下所述。
DateTimeException :如果无法进行调整。ArithmeticException : 如果发生数字溢出。下面的程序说明了adjustInto()方法。
程序1 :
// Java program to demonstrate the adjustInto() method import java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // Current time ZonedDateTime date = ZonedDateTime.now(); // Prints the current date System.out.println("Current date is: " + date); // Parses the date OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); // Function used date = (ZonedDateTime)date1.adjustInto(date); // Prints the date System.out.println(date); }}
输出。
Current date is: 2018-12-11T09:53:15.294Z[Etc/UTC]2018-12-12T13:30:30Z[Etc/UTC]
程序2 :
// Java program to demonstrate the adjustInto() method// exceptions import java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { try { // Current time ZonedDateTime date = ZonedDateTime.now(); // Prints the current date System.out.println("Current date is: " + date); // Parses the date OffsetDateTime date1 = OffsetDateTime.parse("2018-13-12T13:30:30+05:00"); // Function used date = (ZonedDateTime)date1.adjustInto(date); // Prints the date System.out.println(date); } catch (Exception e) { System.out.println(e); } }}输出。
Current date is: 2018-12-11T09:53:24.660Z[Etc/UTC]java.time.format.DateTimeParseException: Text '2018-13-12T13:30:30+05:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13
参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjuster.html
