解析ISO 8601日期格式,如2015-06-27T13:16:37.363Z在Java中 [英] Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java
问题描述
我正在使用 SimpleDateFormat
来解析 String
。
这是我当前的代码:
public String getCreatedDateTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddEHH:mm:ss.zzzz");
try {
Date date = simpleDateFormat.parse("2015-06-27T13:16:37.363Z");
return date.toString();
} catch (ParseException e) {
return "Error parsing date";
}
}
正如你所看到的,我只是把一个常数parse()方法用于测试目的。
As you can see, I just put a constant in the parse() method for testing purposes.
所以,这是我要解析的:
So, this is what I am trying to parse:
2015-06-27T13:16:37.363Z
2015-06-27T13:16:37.363Z
这是 SimpleDateFormat我使用的
模式:
yyyy-MM-ddEHH:mm:ss.zzzz
yyyy-MM-ddEHH:mm:ss.zzzz
我不断得到ParseException。
I keep getting the ParseException.
我知道这是可以理由的。 zzzz在最后,但我不知道什么.363Z可能代表,所以我只是使用一些随机的字母。不好的想法。
I know that it is proably because of the .zzzz at the end but I have no idea what .363Z might stand for so I just used some random letters. Bad idea.
我会很感激你的帮助。谢谢!
I'll appreciate your help a lot. Thank you!
推荐答案
尝试使用此模式(注意结尾处的X和中间的T):
Try with this pattern (note the X at the end and the 'T' in the middle):
"yyyy-MM-dd'T'HH:mm:ss.SSSX"
从Java的 SimpleDateFormat的文档:
ISO 8601时区:
ISO 8601 Time zone:
...
对于解析,Z被解析为UTC时区指示符。
For parsing, "Z" is parsed as the UTC time zone designator.
另外,从描述不同字符的部分,
And, from the part where it describes the different characters:
X - 时区 - ISO 8601时区
X - Time zone - ISO 8601 time zone
编辑
如果使用Android,则不支持X。
If using Android, then "X" is not supported.
您可以使用此模式(请注意Z是现在的一个文字):
You can use this pattern (note Z is a literal now):
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
但是,您将获得当前时区的日期,并需要将其转换为UTC如果需要的话。
But then you'll get the date on your current timezone and would need to convert it to UTC if needed.
这篇关于解析ISO 8601日期格式,如2015-06-27T13:16:37.363Z在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!