I'm trying to write a class, which able to parse multi-format and multi-locale strings into DateTime
.
multi-format
means that date might be: dd/MM/yyyy
, MMM dd yyyy
, ... (up to 10 formats)
multi-locale
means that date might be: 29 Dec 2015
, 29 Dez 2015
, dice 29 2015
... (up to 10 locales, like en
, gr
, it
, jp
)
Using the answer Using Joda Date & Time API to parse multiple formats I wrote:
val locales = List(
Locale.ENGLISH,
Locale.GERMAN,
...
)
val patterns = List(
"yyyy/MM/dd",
"yyyy-MM-dd",
"MMMM dd, yyyy",
"dd MMMM yyyy",
"dd MMM yyyy"
)
val parsers = patterns.flatMap(patt => locales.map(locale => DateTimeFormat.forPattern(patt).withLocale(locale).getParser)).toArray
val birthDateFormatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter
but it doesn't work:
birthDateFormatter.parseDateTime("29 Dec 2015") // ok
birthDateFormatter.parseDateTime("29 Dez 2015") // exception below
Invalid format: "29 Dez 2015" is malformed at "Dez 2015"
java.lang.IllegalArgumentException: Invalid format: "29 Dez 2015" is
malformed at "Dez 2015"
I found what all parsers: List[DateTimeParser]
had "lost" their locales after an appending into birthDateFormatter: DateTimeFormatter
. And birthDateFormatter
has only one locale - en
.
I can write:
val birthDateFormatter = locales.map(new DateTimeFormatterBuilder().append(null, parsers).toFormatter.withLocale(_))
and use it like:
birthDateFormatter.map(_.parseDateTime(stringDate))
but it will throw a lots of exceptions. It's terrible.
How can I parse multi-format and multi-locale strings using joda-time? How can I do it any other way?