Java Month adjustInto()方法

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

Java Month adjustInto()方法

java.time.Month ENUM的adjustInto()方法是Java中的一个内置函数,它接收一个指定日期的Temporal对象,并返回一个与输入的可观察类型相同的新Temporal对象,其中的月份被替换成这个年月。

方法声明 :

public Temporal adjustInto(Temporal temporal)

语法:

Temporal newLocalDate = Month.ANYMONTH.adjustInto(Temporal temporal)

参数 :该方法以temporal为参数,其中。

temporal – 是要调整的指定日期。ANYMONTH – 是指定的要调整的日期的月份,例如,一月,二月,等等。newLocalDate – 是修改后的日期。

返回值 :该函数返回一个调整后的时间对象,它是根据指定的月份调整的日期。

异常情况

DateTimeException : 如果不可能进行调整,该方法会抛出这个异常。ArithmeticException :如果发生数字溢出,则抛出此异常。

下面的程序说明了上述方法。

程序1 :

import java.time.*;import java.time.Month;import java.time.temporal.Temporal;  class DayOfWeekExample {    public static void main(String[] args)    {        // Set a Local Date whose month is found        LocalDate localDate1            = LocalDate.of(1947, Month.AUGUST, 15);          // Find the month from the Local Date        Month monthOfYear1            = Month.from(localDate1);          // Printing the Local Date        System.out.println(localDate1                           + " which is "                           + monthOfYear1.name());          // Adjust the month to JANUARY from AUGUST        Temporal localDate2            = Month.JANUARY                  .adjustInto(localDate1);          // Find the day from the new Local date        Month monthOfYear2            = Month.from(localDate2);          // Printing the new Local Date        System.out.println(localDate2                           + " which is "                           + monthOfYear2.name());    }}

输出。

1947-08-15 which is AUGUST1947-01-15 which is JANUARY

程序2 :

import java.time.*;import java.time.Month;import java.time.temporal.Temporal;  class DayOfWeekExample {    public static void main(String[] args)    {        // Set a Local Date whose month is found        LocalDate localDate1            = LocalDate.of(2019, Month.MARCH, 18);          // Find the month from the Local Date        Month monthOfYear1            = Month.from(localDate1);          // Printing the Local Date        System.out.println(localDate1                           + " which is "                           + monthOfYear1.name());          // Adjust the month to December from March        Temporal localDate2            = Month.DECEMBER                  .adjustInto(localDate1);          // Find the day from the new Local date        Month monthOfYear2            = Month.from(localDate2);          // Printing the new Local Date        System.out.println(localDate2                           + " which is "                           + monthOfYear2.name());    }}

输出。

2019-03-18 which is MARCH2019-12-18 which is DECEMBER

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

相关推荐