admin管理员组文章数量:1310633
Is DateTimeFormatter missing ofYearMonth() method?
It has
ofLocalizedDateTime()
ofLocalizedDate()
ofLocalizedTime()
If using ofPattern(), it is not locale sensitive.
Is DateTimeFormatter missing ofYearMonth() method?
It has
ofLocalizedDateTime()
ofLocalizedDate()
ofLocalizedTime()
If using ofPattern(), it is not locale sensitive.
Share Improve this question edited Feb 3 at 9:10 Anonymous 86.4k15 gold badges162 silver badges177 bronze badges asked Feb 3 at 6:16 eastwatereastwater 5,64013 gold badges69 silver badges148 bronze badges 4 |1 Answer
Reset to default 4Yes.
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.
本文标签: javaIs DateTimeFormatter missing ofYearMonth() methodStack Overflow
版权声明:本文标题:java - Is DateTimeFormatter missing ofYearMonth() method? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741835169a2400171.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
ofLocalizedPattern
added in Java 19. – Slaw Commented Feb 3 at 6:34YearMonthStyle
... and a lot more combinations (YearDayOfYear
,YearQuarterOfYear
,YearWeekOfYear
, ...) that is why we can (must) use patterns (orDateTimeFormatterBuilder
) -- maybe because it is not expected to be used that often – user85421 Commented Feb 3 at 7:48DateTimeFormatter
. – Anonymous Commented Feb 3 at 9:08