Java 中的 OffsetDateTime getDayOfMonth() 方法及示例

2025 年 1 月 6 日 | 阅读 2 分钟

通过 Java OffsetDateTime 类的 getDayOfMonth() 函数可以获取每月的天数属性。

语法

参数:此方法不接受任何参数。

返回值:返回给定月份的日期,范围可以从 1 到 31。

示例 1

在提供的代码中,使用给定的日期和时间(2024 年 6 月 26 日,09:30 UTC)初始化一个 OffsetDateTime 实例。然后使用 getDayOfMonth() 方法从该日期时间实例中获取月份中的天数。该值存储在 dayOfMonth 变量中,表示该月的天数(在此示例中为 26)。然后,程序会显示此值以及一条消息,说明指定月份的日期。此示例以基本方式演示了如何使用 OffsetDateTime 的 getDayOfMonth() 方法来提取和显示给定日期时间中的月份天数。

实施

文件名: GetDayMonthExample1.java

输出

 
The Day of the given month is: 26  

示例 2

所提供的代码使用 now 函数并配合正确的 ZoneOffset 来创建 UTC 和 EST 时区的 OffsetDateTime 实例。之后,它使用 getDayOfMonth 方法从这些日期时间实例中提取月份中的天数。最后,代码会打印出 UTC 和 EST 时区的日期、时间和月份的天数。这展示了如何在 Java 中处理不同时区并提取特定的日期时间组件。

实施

文件名: GetDayMonthExample2.java

输出

 
The UTC date and time is given by 2024-06-26T17:57:09.690173598Z and the Day of the month is: 26
The EST date and time is given by 2024-06-26T12:57:09.690297391-05:00 and the Day of the month is: 26