Java OffsetTime adjustInto()方法及示例

来源:这里教程网 时间:2026-02-17 21:00:23 作者:

Java OffsetTime adjustInto()方法及示例

Java中OffsetDateTime类的 adjustInto() 方法将指定的时间对象调整为与此对象相同的时间。

语法:

public Temporal adjustInto(Temporal temporal)

参数: 该方法接受一个 Temporal 参数,指定要调整的目标对象,不为空。

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

错误和异常: 该方法抛出两个异常,如下所述。

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]

程序2 :

// 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://docs.oracle.com/javase/8/docs/api/java/time/OffsetTime.html#adjustInto-java.time.temporal.Temporal-

相关推荐