Date Time Formatter use same pattern but different output with similar date string format

80 Views Asked by At

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 ?

2

There are 2 best solutions below

2
On

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 that Locale object explicitly rather than rely upon the default.

Locale locale = Locale.US ;
DateTimeFormatter f = 
    DateTimeFormatter
        .ofPattern( "dd MMM yyyy, HH:mm:ss" )
        .withLocale( locale ) ;  // ⬅️ Specify locale.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

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.

String input = "2023-12-10T20:23:53" ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
0
On

Locale matters but you can also use parseCaseInsensitive();

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    builder.parseCaseInsensitive();
    builder.appendPattern(formatDate);
    DateTimeFormatter formatter = builder.toFormatter(Locale.ENGLISH);