I want names of all days in a week, but i have to create Enum(can be achieved by other ways too).
Another way is to get the constant from calendar class and store them manually in Collection.
But, Is there any method in Java Date-Time API to get Collection of all Days name
in a week or Collection of all months name
in year.
Yes you can using DateFormatSymbols
:
DateFormatSymbols symbols = new DateFormatSymbols(new Locale("en"));
String[] days = symbols.getWeekdays();
String[] months = symbols.getMonths();
There are also methods for short names (for en
it would be Sat
etc.) and of course you can choose your locale. Works with Java 1.6+.
@Edit: as to why this returns 8 values for days, if you check the Calendar
class they start counting days from 1 to 7 so I guess DateFormatSymbols
doesn't want to fool around with subtracting one and they just went with an array of size 8.
@Edit2: in the source code you can see:
* Weekday strings. For example: "Sunday", "Monday", etc. An array
* of 8 strings, indexed by <code>Calendar.SUNDAY</code>,
* <code>Calendar.MONDAY</code>, etc.
* The element <code>weekdays[0]</code> is ignored.
So as I said they are simply using Calendar
values as indices, that's all.