在 Java 中解析 ISO 8601 日期格式,如 2015-06-27T13:16:37.363Z [英] Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java
问题描述
我正在尝试使用 SimpleDateFormat
解析 String
.
I am trying to parse a String
using SimpleDateFormat
.
这是我当前的代码:
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
模式:
This is the SimpleDateFormat
pattern that I am using:
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 的文档:
From Java's SimpleDateFormat's documentation:
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.
这篇关于在 Java 中解析 ISO 8601 日期格式,如 2015-06-27T13:16:37.363Z的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!