I have multiple files which contains many date time strings. Example :
File 1 :
string date = 30 Nov 2023, 18:15:53
format = dd MMM yyyy, HH:mm:ss
result => success formatted (2023-11-30T22:46:48)
File 2 :
string date = 10 Dec 2023, 20:23:53
format = dd MMM yyyy, HH:mm:ss
result => Text '10 Dec 2023, 20:23:53' could not be parsed at index 3
DateTimeFormatter dFormatter = DateTimeFormatter.ofPattern(formatDate);
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeString, dFormatter);
Why does it produce different results ? And how do I solve this ?
Locale
When parsing localized formats such as yours, a
Locale
object determines the human language and cultural norms used in translating name of month, punctuation, etc.If you choose to not specify a
Locale
, the JVM’s current default locale is used implicitly. If you have a specific locale in mind, I suggest always specifying thatLocale
object explicitly rather than rely upon the default.ISO 8601
The ideal solution would be educating the publisher of your data about using only standard ISO 8601 formats when exchanging date-time values as text. Localized formats should be used only for presentation to the user, never for data storage nor data exchange.
The java.time classes use ISO 8601 formats by default when parsing/generating text. So no need to specify a formatting pattern.