I have the following code:
public static String convert( final String date )
{
final DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.appendOptional( DateTimeFormatter.ofPattern( "dd-MM-yyyy" ) )
.appendOptional( DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
.appendOptional( DateTimeFormatter.ofPattern( "E MMM dd yyyy" ) )
.parseDefaulting( ChronoField.HOUR_OF_DAY, 0 )
.parseDefaulting( ChronoField.MINUTE_OF_HOUR, 0 )
.parseDefaulting( ChronoField.SECOND_OF_MINUTE, 0 );
final LocalDateTime dateTime = LocalDateTime.parse( date, dateTimeFormatterBuilder.toFormatter() );
return dateTime.format( DateTimeFormatter.ofPattern( "dd-MM-yyyy" ) );
}
But when the date is the following: Tue Apr 19 2022
It fails to convert but it shouldn't since the "E MMM dd yyyy" is there.
java.time.format.DateTimeParseException: Text 'Tue Apr 19 2022' could not be parsed, unparsed text found at index 0
Thanks
CodePudding user response:
Should it be?
"EEE MMM dd yyyy"
CodePudding user response:
Specify Locale
Specify a locale, to determine a human language and culture to use in translation.
final DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.appendOptional( DateTimeFormatter.ofPattern( "dd-MM-yyyy" ) )
.appendOptional( DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
.appendOptional( DateTimeFormatter.ofPattern( "E MMM dd yyyy" ) )
.parseDefaulting( ChronoField.HOUR_OF_DAY, 0 )
.parseDefaulting( ChronoField.MINUTE_OF_HOUR, 0 )
.parseDefaulting( ChronoField.SECOND_OF_MINUTE, 0 );
String input = "Tue Apr 19 2022" ;
Locale locale = Locale.US ;
final LocalDateTime ldt = LocalDateTime.parse( input , dateTimeFormatterBuilder.toFormatter().withLocale( locale ) );
System.out.println ( ldt ) ;
See this code run live at IdeOne.com.
2022-04-19T00:00