【问题标题】:String to LocalDateTime conversion : java.time.format.DateTimeParseException [duplicate]字符串到 LocalDateTime 的转换:java.time.format.DateTimeParseException [重复]
【发布时间】:2018-08-09 16:54:16
【问题描述】:

我正在使用下面的代码来转换字符串中的日期:

    String strDate="Thu Aug 09 16:01:46 IST 2018";        
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    LocalDateTime dateTime = LocalDateTime.parse(strDate,formatter);

我收到以下异常:

java.time.format.DateTimeParseException: Text 'Thu Aug 09 16:01:46 IST 2018' could not be parsed at index 0

变量“strDate”中的格式将是相同的,并且无法修改,因为我将从不同的应用程序中获取该格式

【问题讨论】:

  • 我需要将输入字符串转换为'yyyy-MM-dd HH:mm:ss.SSS'格式。
  • 输入字符串的模式应该与解析器匹配,一旦你从解析器获得日期,然后再次将日期转换为你想要的模式。这是一个两步过程

标签: java dateformatter


【解决方案1】:

输入字符串的日期格式为:E MMM dd HH:mm:ss z yyyy。下面的代码应该可以正常工作

public static void main(String[] args) throws IOException {
    String strDate = "Thu Aug 09 16:01:46 IST 2018";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy");
    LocalDateTime dateTime = LocalDateTime.parse(strDate, formatter);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-30
    • 2019-11-27
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    相关资源
    最近更新 更多