将UTC字符串通过SimpleDateFormat解析为Date时出现无法解析的日期错误

时间:2014-07-16 22:22:25

标签: java android parsing date simpledateformat

我正在尝试编写一些内容,这些内容将采用UTC格式的以下格式的字符串,并将其格式化为从手机中获取的本地时区。但是,尽管查看SimpleDateFormat documentation,我仍然遇到错误,我的示例字符串是不可解析的:

W/System.err﹕ java.text.ParseException: Unparseable date: "2014-07-16T21:00:00:000+0000" (at offset 19)
W/System.err﹕ at java.text.DateFormat.parse(DateFormat.java:555)
[...]
D/Set time:﹕ Wed Jul 16 15:10:03 PDT 2014
D/TimeInMilli:﹕ 1405548603565

代码:

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone(); //Get phone's PST zone

String UTCinput = "2014-07-16T21:00:00:000+0000"; //2:00PM PST
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(tz);

Date dateCal = new Date();

try {
    dateCal = format.parse(UTCinput);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

cal.setTime(dateCal);
Log.d("Set time: ", String.valueOf(dateCal));
Log.d("TimeInMilli: ", String.valueOf(cal.getTimeInMillis()));

我正在解析的方式有什么问题?

1 个答案:

答案 0 :(得分:2)

您的输入String需要与您的DateFormat模式匹配

String UTCinput = "2014-07-16T21:00:00.000+0000"; //2:00PM PST
                                      ^--- was ":"