Java year adjustInto()方法及示例
Year 类的 adjustInto() 方法用于调整传递的时间对象,使其具有该方法所适用的年份。该实例是不可改变的,不受该方法调用的影响。
语法
public Temporal adjustInto(Temporal temporal)
参数: 该方法接受 temporal 作为参数,它是要调整的目标时间对象。它不应该是空的。
返回值: 该方法返回调整后的对象。
异常: 该方法会抛出以下异常。
DateTimeException – 如果不能进行调整。ArithmeticException – 如果发生数字溢出。下面的程序说明了adjustInto()方法:
程序1 :
// Java program to demonstrate// Year.adjustInto() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Year object Year yr = Year.of(2019); // create a temporal object LocalDate date = LocalDate.parse("2007-12-03"); // print instance System.out.println("LocalDate :" + date); // apply adjustInto method of Year class LocalDate updatedlocal = (LocalDate)yr.adjustInto(date); // print instance System.out.println("LocalDate after" + " applying adjustInto method: " + updatedlocal); }}
输出:
LocalDate :2007-12-03LocalDate after applying adjustInto method: 2019-12-03
程序2
// Java program to demonstrate// Year.adjustInto() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Year object Year yr = Year.of(2032); // create a temporal object LocalDate date = LocalDate.parse("2017-01-13"); // print instance System.out.println("LocalDate :" + date); // apply adjustInto method of Year class LocalDate updatedlocal = (LocalDate)yr.adjustInto(date); // print instance System.out.println("LocalDate after" + " applying adjustInto method: " + updatedlocal); }}输出:
LocalDate :2017-01-13LocalDate after applying adjustInto method: 2032-01-13
**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/time/Year.html#adjustInto(java.time.temporal.Temporal)。
