Skip to content
Advertisement

How to parse DateTime with Time between the dates?

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

JavaScript

Result:

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

Advertisement

Answer

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement