📜  Java中的月份adjustInto()方法

📅  最后修改于: 2022-05-13 01:54:59.695000             🧑  作者: Mango

Java中的月份adjustInto()方法

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

方法声明

public Temporal adjustInto(Temporal temporal)

语法

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

参数:此方法将时间作为参数,其中:

  • temporal – 是要调整的指定日期。
  • ANYMONTH – 是日期要调整到的指定月份,例如 JANUARY、FEBRUARY 等。
  • newLocalDate – 是修改日期。

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

例外

  • 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 AUGUST
1947-01-15 which is JANUARY

方案二

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 MARCH
2019-12-18 which is DECEMBER

参考:https: Java/time/Month.html#adjustInto-java.time.temporal.Temporal-