3

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?

Tom
  • 1,414
  • 12
  • 21
  • HAve you looked at the DateTimeFormatterBuilder in JodaTime? Seems it could create what you're looking for. – Jonathan Drapeau Jun 19 '13 at 13:10
  • Yes, I did, but I couldn't figure out how to print the separator characters locale-specific. It doesn't seem to be supported. – Tom Jun 19 '13 at 13:14
  • That would be the "Hardest" part of creating the pattern, you would need to get the separator from a locally formatted date and add it to the builder as a literal. – Jonathan Drapeau Jun 19 '13 at 13:19
  • That would certainly be a possibility to determine the separator character. Unfortunately, it's not sufficient. There are more locale-specific characteristics to deal with, like the order of the date fields, which can't be determined so easily. A US date is formatted like month-day-year, but normal people format it like day-month-year :-) – Tom Jun 19 '13 at 13:28

2 Answers2

4

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);
herman
  • 11,740
  • 5
  • 47
  • 58
1

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".

herman
  • 11,740
  • 5
  • 47
  • 58
  • 1
    That's not an option. I'm presenting the date to users in a GUI, and must be fully localized for them. That includes the separator characters, but also the order of the date fields. – Tom Jun 19 '13 at 13:07
  • The ISO standard is an international one and is locale-neutral, so that's why I seemed like a possible alternative. – herman Jun 19 '13 at 15:22