Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

java - Jodatime: how to print 4-digit year?

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)

which gives "17/06/13" (2-digit year). The style "M-" gives "17 juin 2013" (locale French), which is also not what I want.

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...