Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...