If this were real work rather than homework, I would:
- Use the java.time objects for date-time work rather than make my own.
- Use an
ArrayList
rather than a array.
The YearMonth
class represents, well, the year-month.
Month
is an enum, with a dozen pre-defined objects, one for each month of the year January-December.
A LocalDate
is a date-only value, without time-of-day and without time zone.
List
is an interface for an ordered collection, and ArrayList
is a particular implementation.
YearMonth ym = YearMonth.of( 2017 , Month.JANUARY ) ;
int monthLength = ym.lengthOfMonth() ;
List< LocalDate > daysInJanuary = new ArrayList<>( monthLength ) ;
for( int i = 1 ; i <= monthLength ; i ++ ) {
LocalDate ld = ym.atDay( i ) ;
daysInJanuary.add( ld ) ;
}
daysInJanuary.toString(): [2017-01-01, 2017-01-02, 2017-01-03, 2017-01-04, 2017-01-05, 2017-01-06, 2017-01-07, 2017-01-08, 2017-01-09, 2017-01-10, 2017-01-11, 2017-01-12, 2017-01-13, 2017-01-14, 2017-01-15, 2017-01-16, 2017-01-17, 2017-01-18, 2017-01-19, 2017-01-20, 2017-01-21, 2017-01-22, 2017-01-23, 2017-01-24, 2017-01-25, 2017-01-26, 2017-01-27, 2017-01-28, 2017-01-29, 2017-01-30, 2017-01-31]
To generate a nicely formatted string representing each date's value, I would let java.time localize automatically.
Locale locale = Locale.CANADA_FRENCH ; // Or Locale.US, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( locale ) ;
for( LocalDate ld : daysInJanuary ) {
String output = ld.format( f ) ;
System.out.println( output ) ;
}
Output is something like this, depending on the Locale
:
Sunday, January 1, 2017
Monday, January 2, 2017
Tuesday, January 3, 2017
…
See this code run live at IdeOne.com. But be aware that IdeOne.com is limited to only a single Locale
, Locale.US
.