【问题标题】:How can I get the list of days of each month in the "JODA" library?如何在“JODA”库中获取每个月的天数列表?
【发布时间】:2022-01-18 07:15:00
【问题描述】:

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

【问题讨论】:

    标签: java android kotlin android-jodatime


    【解决方案1】:

    tl;博士

    使用 java.timeJoda-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 8 及更高版本中的 java.time 类。 Android 26+ 有一个实现。对于早期的 Android,最新的 Gradle 工具通过 «API desugaring» 提供了大部分 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() ;
    

    【讨论】:

    • 我的最低版本是21,java.time有错误
    • @saeednoshadi 正如我所说,您需要使用最新的 Gradle 工具。搜索“API 脱糖”以了解更多信息。如果这对您不起作用,请在 ThreeTenABP 库中添加 Android 适配的 back-port。
    • 我可以使用 DateTime 类获取月份名称列表吗?
    • @saeednoshadi Month#getDisplayName。我建议您花一些时间仔细阅读 java.time 类。并阅读 Oracle 的免费教程。
    猜你喜欢
    • 2020-03-28
    • 2011-04-15
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多