简体   繁体   中英

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?

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

As an alternative you could opt to use the ISO standard date format instead of a localized one. ISODateTimeFormat.date() will return a formatter for "yyyy-MM-dd".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM