0

I am having this error time when I tried to format a date. here is the code snippet.

private LocalDate expirationDate;

public static String convertIntlToStandard(String dateTpChange) {
    if(StringUtils.isNotBlank(dateTpChange)) {
        DateTimeFormatter oldformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate formatDateTime = LocalDate.parse(dateTpChange, oldformatter);
        DateTimeFormatter newformatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        return formatDateTime.format(newformatter);
    } else {
        return dateTpChange;
    }
}

boPrescriptionResponse.setExpirationDate(LocalDate.parse(DateUtils.convertIntlToStandard(boPrescription.getExpirationDate().toString())));

java.time.format.DateTimeParseException: Text '06/05/2019' could not be parsed at index 0

Robert
  • 7,394
  • 40
  • 45
  • 64
edman
  • 11
  • Does this help https://stackoverflow.com/questions/60949513/unable-to-parse-string-into-java-8-localdatetime/60949757?noredirect=1#comment107831974_60949757 – Shubham Apr 15 '20 at 04:33
  • 3
    that is to be expected. As you try to parse a string with the pattern `MM/dd/yyyy` with a formatter for `yyyy-MM-dd` the formatter will not be able to convert the pattern and throw an exception. So you'd need to check the pattern first. Specifically: the year `06/0` is unparseable. – Stefan Helmerichs Apr 15 '20 at 04:49
  • Why do you expect the `dateTpChange` string value of `"06/05/2019"` would parse without error when using a formatter with pattern `"yyyy-MM-dd"`? – Andreas Apr 15 '20 at 05:04
  • Does this answer your question? [Unable to parse string into Java 8 LocalDateTime](https://stackoverflow.com/questions/60949513/unable-to-parse-string-into-java-8-localdatetime) – Umair Khan Apr 15 '20 at 12:23
  • The naming of your method is ambiguous, as `yyyy-MM-dd` is the standard (ISO-8601). – Mark Rotteveel Apr 16 '20 at 15:56

1 Answers1

0

It looks like you switched oldformatter and newformatter:

public static String convertIntlToStandard(String dateTpChange) {
    if(StringUtils.isNotBlank(dateTpChange)) {
        DateTimeFormatter oldformatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        LocalDate formatDateTime = LocalDate.parse(dateTpChange, oldformatter);
        DateTimeFormatter newformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return formatDateTime.format(newformatter);
    } else {
        return dateTpChange;
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350