Is DateTimeFormatter missing ofYearMonth() method?
It has
ofLocalizedDateTime()
ofLocalizedDate()
ofLocalizedTime()
If using ofPattern(), it is not locale sensitive.
Yes.
By digging into the JDK source code, we can see that the class responsible for formatting localised date/times is LocalizedPrinterParser
. This class has three fields - dateStyle
, timeStyle
, and requestedPattern
. The former two fields are set by ofLocalizedDateTime
, ofLocalizedDate
, and ofLocalizedTime
. requestedPattern
is set by ofLocalizedPattern
.
That's all DateTimeFormatter
currently supports for localised formats, The closest to a ofLocalizedYearMonth
would be to use a pattern such as yyyyMM
in ofLocalizedPattern
. Example:
System.out.println(
DateTimeFormatter
.ofLocalizedPattern("yyyyMM")
.withLocale(Locale.CHINESE).format(LocalDate.now())
);
// prints 公元2025年2月
Unlike the other three methods, you cannot specify a FormatStyle
, but there might be other pattern strings available for a given locale that produce a longer/shorter output.
The available patterns for each locale can be found in the CLDR repo, under the <availableFormats>
tag in the XML file for a given locale. For example, here is where all the available formats for English for the Gregorian calendar is listed. This page explains how the requested pattern is matched against the ones in the CLDR.
Note that Java's APIs closely match how the formats are specified in the XML files in CLDR. The different format styles for dates are listed under the <dateFormats>
tag, the format styles for times are listed under the <timeFormats>
tag, and similarly for the <dateTimeFormats>
tag. There is no <yearMonthFormats>
or anything like that.
So unless the CLDR updates its format to include something like that, there is not much that the JDK can do.