当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java LocalDateTime adjustInto()用法及代码示例


LocalDateTime类adjustInto()方法

  • adjustInto() 方法可在java.time包。
  • adjustInto() 方法用于将此 LocalDateTime 对象调整为给定的 Temporal 对象,或者换句话说,我们可以说调整后的对象具有此对象表示的相同日期和时间。
  • adjustInto() 方法是一个非静态方法,它只能通过类对象访问,如果我们尝试使用类名访问方法,那么我们将得到一个错误。
  • adjustInto() 方法可能会在调整 Date-Time 时抛出异常。
    • DateTimeException - 当给定参数无法调整此 LocalDateTime 时,可能会引发此异常。
    • ArithmeticException - 当计算结果超过此日期的长度时,可能会引发此异常。

用法:

    public Temporal adjustInto(Temporal temp);

参数:

  • Temporal temp- 表示要调整此 LocalDateTime 的时间对象。

返回值:

这个方法的返回类型是Temporal,它返回 Temporal 对象,该对象保存将此对象日期时间调整为给定对象的值。

例:

// Java program to demonstrate the example 
// of adjustInto(Temporal temp) method 
// of LocalDateTime

import java.time.*;

public class AdjustIntoOfLocalDateTime {
    public static void main(String args[]) {
        // Instantiates two LocalDateTime
        // and a ZonedDateTime object
        LocalDateTime da_ti1 = LocalDateTime.parse("2005-10-05T10:10:10");
        LocalDateTime da_ti2 = LocalDateTime.now();
        ZonedDateTime zo_da_time = ZonedDateTime.parse("2008-08-08T20:20:20.213+03:00[Africa/Asmara]");

        // Display da_ti1, da_ti2
        // and zo_da_time
        System.out.println("LocalDateTime da_ti1 and da_ti2:");
        System.out.println("da_ti1:" + da_ti1);
        System.out.println("da_ti2:" + da_ti2);
        System.out.println();
        System.out.println("ZonedDateTime zo_da_time:");
        System.out.println("zo_da_time:" + zo_da_time);

        System.out.println();

        // Here, this method adjusts this object
        // into the given object i.e. here we are
        // adjusting this LocalDateTime(da_ti1)
        // into the given object ZonedDateTime(zo_da_time)
        // and the given object is to have same
        // date and time as this object da_ti1
        zo_da_time = (ZonedDateTime) da_ti1.adjustInto(zo_da_time);

        // Display updated zo_da_time
        System.out.println("da_ti1.adjustInto(zo_da_time):" + zo_da_time);

        // Here, this method adjusts this object
        // into the given object i.e. here we are
        // adjusting this LocalDateTime(da_ti2)
        // into the given object ZonedDateTime(zo_da_time)
        // and the given object is to have same
        // date and time as this object da_ti2
        zo_da_time = (ZonedDateTime) da_ti2.adjustInto(zo_da_time);

        // Display updated zo_da_time
        System.out.println("da_ti2.adjustInto(zo_da_time):" + zo_da_time);
    }
}

输出

LocalDateTime da_ti1 and da_ti2:
da_ti1:2005-10-05T10:10:10
da_ti2:2020-06-04T07:51:48.984048

ZonedDateTime zo_da_time:
zo_da_time:2008-08-08T20:20:20.213+03:00[Africa/Asmara]

da_ti1.adjustInto(zo_da_time):2005-10-05T10:10:10+03:00[Africa/Asmara]
da_ti2.adjustInto(zo_da_time):2020-06-04T07:51:48.984048+03:00[Africa/Asmara]


相关用法


注:本文由纯净天空筛选整理自 Java LocalDateTime Class | adjustInto() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。