Java ChronoLocalDate adjustInto()方法及示例
Java中 ChronoLocalDate 接口的 adjustInto() 方法用于调整指定的时间对象,使其与此对象的日期相同。
语法:
public Temporal adjustInto(Temporal temporal)
参数 :该方法接受一个临时参数,该参数是要调整的目标对象,而不是具体的null。
返回值 : 它返回调整后的对象,而不是null。
异常 : 该函数会抛出两个异常,如下所述。
- DateTimeException : 如果程序无法进行调整,就会抛出这个异常。ArithmeticException :如果有数字溢出,程序会抛出这个异常。
以下程序说明了Java中ChronoLocalDate的adjustInto()方法。
程序1 :
// Program to illustrate the adjustInto() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { ZonedDateTime date = ZonedDateTime.now(); // prints the date System.out.println(date); // Parses the date ChronoLocalDate date1 = LocalDate.parse("2015-01-31"); // Uses the function to adjust the date date = (ZonedDateTime)date1.adjustInto(date); // Prints the adjusted date System.out.println(date); }}
输出。
2019-04-28T19:58:13.775Z[Etc/UTC]2015-01-31T19:58:13.775Z[Etc/UTC]
程序2 :说明异常情况。下面的程序抛出一个异常,因为二月是28天而不是31天。
// Program to illustrate the adjustInto() method// Exception Program import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { try { ZonedDateTime date = ZonedDateTime.now(); // prints the date System.out.println(date); // Parses the date ChronoLocalDate date1 = LocalDate.parse("2015-02-31"); // Uses the function to adjust the date date = (ZonedDateTime)date1.adjustInto(date); // Prints the adjusted date System.out.println(date); } catch (Exception e) { System.out.println(e); } }}输出。
2019-04-28T19:58:17.219Z[Etc/UTC]java.time.format.DateTimeParseException: Text '2015-02-31' could not be parsed: Invalid date 'FEBRUARY 31'
参考资料 : https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDate.html#adjustInto-java.time.temporal.Temporal-
