Reputation:
The date I fetched from an open API is 2021-04-28
. I want to format it in this way: 4/28/2021
. Below is the method I tried:
public String formatDateFetchedFromAPI(String transDate) {
LocalDate apiDate = LocalDate.parse(transDate, DateTimeFormatter.BASIC_ISO_DATE);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
String actualDate = formatter.format(apiDate);
return actualDate;
}
This throws an error saying:
java.time.format.DateTimeParseException: Text '2021-04-28' could not be parsed at index 4
If the data that I pull from open API is 20210426
then this method works just fine and returns 4/28/2021
.
Upvotes: 1
Views: 578
Reputation: 60046
Your date looks like an ISO_LOCAL_DATE
and not BASIC_ISO_DATE
, so instead you can just use
LocalDate apiDate = LocalDate.parse(transDate);
without DateTimeFormatter
, because LocalDate.parse
by default uses ISO_LOCAL_DATE
.
Upvotes: 2