📜  Java中的 YearMonth atDay() 方法

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

Java中的 YearMonth atDay() 方法

Java中 YearMonth 类的 atDay() 方法将当前年月与作为参数传递给它的月日结合起来创建一个 LocalDate。

语法

public LocalDate atDay(int dayOfMonth)

参数:此方法接受单个参数dayOfMonth 。这是使用日期。它可以取 1 到 31 之间的值。

返回值:它返回由当前年月和作为参数传递给函数的一个月中的某一天形成的本地日期。

异常:如果参数中传递的月份日期无效,则此方法抛出DateTimeException

下面的程序说明了Java中 YearMonth 的 atDay() 方法:

程序 1

Java
// Program to illustrate the atDay() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
 
        // Creates a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2017, 8);
 
        // Creates a local date with this
        // YearMonth object and day passed to it
        LocalDate date = thisYearMonth.atDay(31);
 
        System.out.println(date);
    }
}


Java
// Program to illustrate the atDay() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
 
        // Creates a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2017, 9);
 
        try {
            // Creates a local date with this
            // YearMonth object and day passed to it
            LocalDate date = thisYearMonth.atDay(31);
 
            System.out.println(date);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


输出:
2017-08-31

程序2 :说明异常。下面的程序抛出异常,因为 9 月是 30 天而不是 31 天。

Java

// Program to illustrate the atDay() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
 
        // Creates a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2017, 9);
 
        try {
            // Creates a local date with this
            // YearMonth object and day passed to it
            LocalDate date = thisYearMonth.atDay(31);
 
            System.out.println(date);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.time.DateTimeException: Invalid date 'SEPTEMBER 31'

参考:https: Java/time/YearMonth.html#atDay-int-