如何在 "JODA" 库中获取每个月的天数列表?

How can I get the list of days of each month in the "JODA" library?

我需要在 JODA 库中获取每个月的天数列表。我该怎么做?

tl;博士

使用 java.time,继承 Joda-Time

yearMonth               // An instance of `java.time.YearMonth`.
.atDay( 1 )             // Returns a `LocalDate` object for the first of the month.
.datesUntil(            // Get a range of dates.
    yearMonth
    .plusMonths( 1 )    // Move to the following month.
    .atDay( 1 )         // Get the first day of that following month, a `LocalDate` object.
)                       // Returns a stream of `LocalDate` objects.
.toList()               // Collects the streamed objects into a list. 

对于没有 Stream#toList 方法的旧版本 Java,请使用 collect( Collectors.toList() )

java.time

Joda-Time 项目现在处于维护模式。该项目建议转移到它的后继者,即 JSR 310 中定义的 java.time 类 并内置于 Java 8 及更高版本中。 Android 26+ 有实现。对于早期的 Android,最新的 Gradle 工具通过 « API 脱糖 » 提供大部分 java.time 功能。

YearMonth

指定月份。

YearMonth ym = YearMonth.now() ;

询问其长度。

int lengthOfMonth = ym.lengthOfMonth() ;

LocalDate

要获取日期列表,请获取该月的第一个日期。

LocalDate start = ym.atDay( 1 ) ;

还有个月的第一天。

LocalDate end = ym.plusMonths( 1 ).atDay( 1 ) ;

获取两者之间的日期流。收集到列表中。

List< LocalDate > dates = start.datesUntil( end ).toList() ;