问题描述
是否可以用Java / Kotlin中的区域设置正确的格式格式化日和月(紧凑格式)而不格式化年份?因此,对于英语,应为 9月20日,而对于瑞典语为 9月20日。
Is there a way to format a day and month (in compact form), but not year, in the locale-correct order in Java/Kotlin? So for English it should be "Sep 20" but for Swedish "20 sep.".
为了进行比较,在Cocoa平台上,我可以执行以下操作(在Swift中):
For comparison, on Cocoa platforms, I can do the following (in Swift):
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "sv_SE")
formatter.setLocalizedDateFormatFromTemplate("MMM d")
print(formatter.string(from: Date()))
这将正确地解决问题。 Java SDK是否有等效的功能?我一直尝试使用 DateTimeFormatter
和较旧的 SimpleTimeFormat
API进行各种形式的操作,但是都没有成功。
This will correctly turn things around. Is there an equivalent thing to do with the Java SDKs? I've been trying various forms with both DateTimeFormatter
and the older SimpleTimeFormat
APIs, but no success.
注释:与,我不希望使用包括年份在内的完整媒介格式。我也不希望 DateTimeFormatter.ofPattern( MMM d)
,因为这样在瑞典语中会给出错误的结果,或者也不希望 DateTimeFormatter.ofPattern( d MMM)
,因为这样会产生错误的英语结果。
Notes: Unlike this question, I don't want the full medium format that includes the year. I also don't want either DateTimeFormatter.ofPattern("MMM d")
, since that gives the incorrect result in Swedish, or DateTimeFormatter.ofPattern("d MMM")
, since that gives the incorrect result in English.
推荐答案
不,抱歉。我知道没有Java库会自动将 MMM d
变成 9月20日。
的首选语言环境
No, sorry. I know of no Java library that will automatically turn "MMM d"
around into 20 sep.
for a locale that prefers the day of month before the month abbreviation.
您可以尝试修改这样:
DateTimeFormatter ft =
DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("sv-SE"))
;
但是结果是:
它包括您不要求的年份。
It includes the year, which you didn’t ask for.
高级解决方案将使用类以构建对象。
An advanced solution would use the DateTimeFormatterBuilder
class to build DateTimeFormatter
objects.
DateTimeFormatterBuilder
.getLocalizedDateTimePattern(
FormatStyle.MEDIUM,
null,
IsoChronology.INSTANCE,
Locale.forLanguageTag("sv-SE")
)
此返回 d MMM y
。修改此字符串以删除 y
及其前面的空格。请注意,在其他语言中, y
可能是 yy
, yyyy
或 u
,并且可能不在字符串的最后。将修改后的格式模式字符串传递到 DateTimeFormatter.ofPattern
。
This returns d MMM y
. Modify this string to delete the y
and the space before it. Note that in other languages the y
may be yy
, yyyy
or u
and may not come last in the string. Pass your modified format pattern string to DateTimeFormatter.ofPattern
.
这可能有些不稳定。即使您浏览了所有可用语言环境的格式模式字符串, CLDR (字符串来自何处)可能仍包含一个惊喜。但我认为这是我们能做的最好的事情。如果是我,我会考虑引发异常,以防万一我可以检测到 getLocalizedDateTimePattern
中的字符串看起来不像我知道的修改方式。
It may be shaky. Even if you look through the format pattern strings for all available locales, the next version of CLDR (where the strings come from) might still contain a surprise. But I think it’s the best we can do. If it were me, I’d consider throwing an exception in case I can detect that the string from getLocalizedDateTimePattern
doesn’t look like one I know how to modify.
这篇关于如何在Java中以语言环境正确的顺序格式化日期和月份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!