Jodatime:如何打印4位数年份? [英] Jodatime: how to print 4-digit year?
问题描述
我正在使用Jodatime格式化日期,并且使用它我使用区域设置来格式化特定于区域设置。我希望我的日期格式化为17/06/2013(分隔符必须取决于区域设置),我可以几乎实现
I'm using Jodatime for format a date, and with it I'm using a locale to format it locale-specific. I want my date to be formatted like "17/06/2013" (the separators must depend on the locale), which I can almost achieve with
DateTimeFormat.forStyle("S-").withLocale(myLocale)
给出17/06/13(2位数年份)。风格M-给出17 juin 2013(locale French),这也不是我想要的。
which gives "17/06/13" (2-digit year). The style "M-" gives "17 juin 2013" (locale French), which is also not what I want.
当然我可以创建一个带有模式的格式化程序比如dd / MM / yyyy,它会给我一个4位数的年份,但它不是对语言敏感的。
Of course I can create a formatter with a pattern like "dd/MM/yyyy", which will give me a 4-digit year, but it is not locale-sensitive.
我一直在寻找一种方法修改使用S-样式创建的格式化程序,但似乎不可能。
I have been looking for a way to modify the formatter created with the "S-" style, but it doesn't seem to be possible.
使用此行为获取格式化程序的最简单方法是什么?
What would be the easiest way to get a formatter with this behaviour?
推荐答案
只需获取本地化短样式的模式,并将yy替换为yyyy(如果它尚未存在)。
Just get the pattern for the localized short style and replace "yy" with "yyyy" if it's not already present.
String pattern = DateTimeFormat.patternForStyle("S-", locale);
if (!pattern.contains("yyyy")) {
pattern = pattern.replace("yy", "yyyy");
}
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
这篇关于Jodatime:如何打印4位数年份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!