Parsing String with spaces to Date, lead to ParseException

为君一笑 提交于 2019-12-25 01:18:53

问题


I have date strings in this form Thu Aug 02 00:00:00 GMT+00:00 2012

I have tried to use this method to parse these String in a Date object

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

But doesn't works and I get this error

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

I suppose that the problem is caused by a wrong SimpleDateFormat, but I don't know the right syntax to fix it.


回答1:


You need to adjust the date format to the given string:

EEE MMM dd HH:mm:ss Z yyyy

Make sure use the correct placeholders, case sensitive, etc. Take a look to the Date and Time Patterns.

Sorry, I had a mistake with the 'z' pattern, 'Z' is:

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

Take a look to Locale.US, it is important to apply because the months and and days are in english.




回答2:


Use this date formatting:

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


来源:https://stackoverflow.com/questions/11510713/parsing-string-with-spaces-to-date-lead-to-parseexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!