Month
The best correct Answer is by staszek making clever use of Streams. Here's the same idea but in old-fashioned syntax instead of Streams, plus some comments.
The Month
enum defines a dozen instances, one per month of the year, numbered sanely 1-12 for January-December. The Month.getValues
method returns an array of all twelve instances. We can loop that array using the Java syntax for the ”enhanced for
loop” also known as a “for-each”.
You can ask for a localized name of the month via the getDisplayName
method. Specify a TextStyle
for length of abbreviation, and a Locale
for the human language and cultural norms used in translating.
TextStyle ts = TextStyle.FULL;
Locale l = Locale.CANADA_FRENCH;
for ( Month month : Month.values () ) {
int monthNumber = month.getValue (); // 1-12.
String monthName = month.getDisplayName ( ts , l );
System.out.println ( "month: " + month + " | monthNumber: " + monthNumber + " | monthName: " + monthName );
}
month: JANUARY | monthNumber: 1 | monthName: janvier
month: FEBRUARY | monthNumber: 2 | monthName: février
month: MARCH | monthNumber: 3 | monthName: mars
month: APRIL | monthNumber: 4 | monthName: avril
month: MAY | monthNumber: 5 | monthName: mai
month: JUNE | monthNumber: 6 | monthName: juin
month: JULY | monthNumber: 7 | monthName: juillet
month: AUGUST | monthNumber: 8 | monthName: août
month: SEPTEMBER | monthNumber: 9 | monthName: septembre
month: OCTOBER | monthNumber: 10 | monthName: octobre
month: NOVEMBER | monthNumber: 11 | monthName: novembre
month: DECEMBER | monthNumber: 12 | monthName: décembre
See Oracle Tutorials for:
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.