Java无法解析的日期SimpleDateFormat [英] Java unparsable date SimpleDateFormat

查看:79
本文介绍了Java无法解析的日期SimpleDateFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的约会日期如下:

Sun Dec 29 00:24:09 CET 2019

我有一个实用的小方法,可以将字符串日期从一种格式解析为另一种格式:

I have a little utility method that parses a string date from a format to another:

public String formatDate(String date, String fromFormat, String toFormat) throws Exception {
        SimpleDateFormat from = new SimpleDateFormat(fromFormat);
        SimpleDateFormat to = new SimpleDateFormat(toFormat);
        return to.format(from.parse(date));
    }

但是,在上述日期格式下,我找不到正确的日期格式来指示我的方法.根据 SimpleDateFormat模式文档,它应该是(如果我没记错的话)以下内容(对于 Sun Dec 29 00:24:09 CET 2019 ):

However, with above date format, I do not find the correct date pattern to indicate to my method. According to SimpleDateFormat patterns documentation, it should be (if I am not mistaken), the following (for Sun Dec 29 00:24:09 CET 2019):

"E M d HH:mm:ss z yyyy"

但是,它将引发以下异常:

However, it throws the following exception:

java.text.ParseException: Unparseable date: "Sun Dec 29 00:24:09 CET 2019"
        at java.text.DateFormat.parse(DateFormat.java:366)
        at com.aptar.simulator.Utils.formatDate(Utils.java:60)

该方法的调用方式如下:

The method is called like this:

formatDate(exDate, "E M d HH:mm:ss z yyyy", "dd-MM-yyyy HH:mm:ss");

哪里

exDate = "Sun Dec 29 00:24:09 CET 2019"

推荐答案

日期格式应为

EEE MMM dd HH:mm:ss z yyyy

使用此格式,您的代码可以正常工作.

Your code works fine using this format.

使用 java.time API

using java.time API

LocalDate.parse(datestr, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy")).format("TO DATE PATTERN");

使用java.time包格式化日期的更多详细信息

这篇关于Java无法解析的日期SimpleDateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆