【问题标题】:Parsing String with spaces to Date, lead to ParseException用空格解析字符串到日期,导致 ParseException
【发布时间】:2012-07-15 16:17:24
【问题描述】:

我有这种形式的日期字符串Thu Aug 02 00:00:00 GMT+00:00 2012

我曾尝试使用此方法在 Date 对象中解析这些字符串

public Date fromStringToDate(String data) {
        Date result;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
        try {
            result = sdf.parse(data);
            return result;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

但不起作用,我收到此错误

java.text.ParseException: Unparseable date: "Thu Aug 02 00:00:00 GMT+00:00 2012"

我认为问题是由错误的SimpleDateFormat 引起的,但我不知道修复它的正确语法。

【问题讨论】:

    标签: java android date simpledateformat


    【解决方案1】:

    您需要将日期格式调整为给定的字符串:

    EEE MMM dd HH:mm:ss Z yyyy
    

    确保使用正确的占位符、区分大小写等。查看Date and Time Patterns

    抱歉,'z' 模式有误,'Z' 是:

    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    

    看看Locale.US,申请很重要,因为月份和日期都是英文的。

    【讨论】:

    • 不起作用...同样的错误...可能z的编号不正确:(
    【解决方案2】:

    使用此日期格式:

    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy")
    

    【讨论】:

    • 不起作用...同样的错误...可能z的数量不正确:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多