Home > Software design >  How to parse DateTime with Time between the dates?
How to parse DateTime with Time between the dates?

Time:03-07

I want to parse a date-time variant that has the time in between the dates. Why is the following not working?

DateTimeFormatter.ofPattern("E L  d HH:mm:ss yyyy").parse("Tue Mar  1 01:29:47 2022")

Result:

java.time.format.DateTimeParseException: Text 'Tue Mar 1 01:29:47 2022' could not be parsed at index 4

CodePudding user response:

I think you have to make sure that

  • you provide a specific Locale for abbreviated months and days of week
  • you use the correct characters in the pattern of your DateTimeFormatter

A month of year is parsed using the character M in a pattern and you have to make sure the correct language is used and the amount of Ms meets the requirements (e.g. EEEE will parse a full day of week, like "Monday"). That's ensurable by passing a Locale to the DateTimeFormatter. A pattern with a single d will parse days of month without leading zeros, while dd would require leading zeros to single-digit days of month.

Here's an example parsing two datetimes, one with a single-digit day of month and one

DateTimeFormatter customDtf = DateTimeFormatter.ofPattern(
        "EEE MMM d HH:mm:ss yyyy",
        Locale.ENGLISH
);
    
System.out.println( // parse a datetime with a two-digit day of month
        LocalDateTime.parse("Mon Mar 14 01:29:47 2022", customDtf)
);
System.out.println( // parse a datetime with a one-digit day of month
        LocalDateTime.parse("Tue Mar 1 01:29:47 2022", customDtf)
);

If you execute this sample code in a main, you'll get the following output:

2022-03-14T01:29:47
2022-03-01T01:29:47
  • Related