Java ChronoLocalDateTime adjustInto()方法及示例

来源:这里教程网 时间:2026-02-17 20:40:31 作者:

Java ChronoLocalDateTime adjustInto()方法及示例

Java中 ChronoLocalDateTime 接口的 adjustInto() 方法用于调整指定的时间对象,使其具有与此对象相同的日期。

语法:

default Temporal adjustInto(Temporal temporal)

参数 :该方法接受一个临时参数,该参数是要调整的目标对象,而不是具体的null。

返回值 : 它返回调整后的对象,而不是null。

异常 : 该函数会抛出两个异常,如下所述。

    DateTimeException : 如果程序无法进行调整,就会抛出这个异常。ArithmeticException :如果有数字溢出,程序会抛出这个异常。

以下程序说明了Java中ChronoLocalDateTime的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)    {          LocalDateTime date            = LocalDateTime                  .parse("2018-12-06T19:21:12");          // prints the date        System.out.println(date);          // Parses the date        ChronoLocalDateTime date1            = LocalDateTime.now();          // Uses the function to adjust the date        date = (LocalDateTime)date1.adjustInto(date);          // Prints the adjusted date        System.out.println(date);    }}

输出:

2018-12-06T19:21:122019-05-14T09:39:37.953

程序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 {              LocalDateTime date                = LocalDateTime                      .parse("2018-12-06T19:21:12");              // prints the date            System.out.println(date);              // Parses the date            ChronoLocalDateTime date1                = LocalDateTime.parse("2015-02-31");              // Uses the function to adjust the date            date = (LocalDateTime)date1.adjustInto(date);              // Prints the adjusted date            System.out.println(date);        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

2018-12-06T19:21:12java.time.format.DateTimeParseException: Text '2015-02-31' could not be parsed at index 10

参考资料 : https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDateTime.html#adjustInto-java.time.temporal.Temporal-

相关推荐