【问题标题】:java.time.format.DateTimeParseException: Text '06/05/2019' could not be parsed at index 0java.time.format.DateTimeParseException:无法在索引 0 处解析文本“06/05/2019”
【发布时间】:2020-04-15 04:17:21
【问题描述】:

我在尝试格式化日期时遇到此错误时间。 这是代码sn-p。

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:无法在索引 0 处解析文本“06/05/2019”

【问题讨论】:

  • 这是意料之中的。当您尝试使用yyyy-MM-dd 的格式化程序解析具有模式MM/dd/yyyy 的字符串时,格式化程序将无法转换模式并引发异常。所以你需要先检查模式。具体来说:06/0 的年份是无法解析的。
  • 为什么您期望"06/05/2019"dateTpChange 字符串值在使用带有"yyyy-MM-dd" 模式的格式化程序时会正确解析?
  • 这能回答你的问题吗? Unable to parse string into Java 8 LocalDateTime
  • 您的方法的命名不明确,因为yyyy-MM-dd 是标准 (ISO-8601)。

标签: java


【解决方案1】:

您好像切换了oldformatternewformatter

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;
    }
}

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 2018-04-04
    • 2018-12-12
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多