1

I need to get a list of days each month in the JODA library. how can I do that?

Saeed Noshadi
  • 829
  • 12
  • 34

1 Answers1

2

tl;dr

Using java.time, the successor to 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. 

For older versions of Java without a Stream#toList method, use collect( Collectors.toList() ).

java.time

The Joda-Time project is now in maintenance mode. The project recommends moving to its successor, the java.time classes defined in JSR 310 and built into Java 8 and later. Android 26+ has an implementation. For earlier Android, the latest Gradle tooling makes most of the java.time functionality available via « API desugaring ».

YearMonth

Specify a month.

YearMonth ym = YearMonth.now() ;

Interrogate for its length.

int lengthOfMonth = ym.lengthOfMonth() ;

LocalDate

To get a list of dates, get the first date of the month.

LocalDate start = ym.atDay( 1 ) ;

And the first day of the next month.

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

Get a stream of dates in between. Collect into a list.

List< LocalDate > dates = start.datesUntil( end ).toList() ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • My minimum version is 21. java.time has an error about it – Saeed Noshadi Jan 18 '22 at 07:34
  • @saeednoshadi As I said, you need to use the latest Gradle tooling. Search on “API desugaring” to learn more. If that does not work for you, add the Android adaptation of the back-port, in the *ThreeTenABP* library. – Basil Bourque Jan 18 '22 at 07:39
  • Can I get the list of months' names with DateTime class? – Saeed Noshadi Jan 18 '22 at 08:26
  • @saeednoshadi [`Month#getDisplayName`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Month.html#getDisplayName(java.time.format.TextStyle,java.util.Locale)). I suggest you spend some time perusing the *java.time* classes. And read the free tutorial by Oracle. – Basil Bourque Jan 18 '22 at 08:35