[英]Android - How to parse this date [ 2014-04-23T14:20:00.000-07:00 ]?
I want to convert this date format : 我想转换这种日期格式:
2014-04-23T14:20:00.000-07:00
into a date object so I can use this method to get the difference : 到一个日期对象,所以我可以使用此方法来获得差异:
DateUtils.getDateDifference(DATE_OBJECT);
... ...
I've tried using 'SimpleDateFormat' but it throws an exception, checked the code many times, but doesn't work: 我尝试使用'SimpleDateFormat',但它抛出异常,多次检查代码,但不起作用:
String pubDate = "2014-04-23T14:20:00.000-07:00";
SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss Z", Locale.ENGLISH);
try {
Date pDate = df.parse(pubDate);
pubDate = "This post was published " + DateUtils.getDateDifference(pDate);
} catch (ParseException e) {
Log.e("DATE PARSING", "Error parsing date..");
pubDate = "Couldn't be retrieved.";
}
What is the simplest way to achieve it successfully? 成功实现它的最简单方法是什么?
According to Android documentation (link given in comment of @MarcoAcierno) you need the symbol Z five times to parse the timezone offset. 根据Android文档(@MarcoAcierno评论中给出的链接),您需要符号Z五次来解析时区偏移量。 Note that in Java-6 there is no built-in solution for handling the colon in offset part, but Java-7 has introduced the new symbol X (here three times: XXX). 请注意,在Java-6中,没有用于处理偏移部分中冒号的内置解决方案,但Java-7引入了新符号X(此处三次:XXX)。 Another example for (Android != Java). (Android!= Java)的另一个例子。 So the final pattern looks like: 所以最终的模式如下:
SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
java.util.Date d = sdf.parse("2014-04-23T14:20:00.000-07:00");
Specifying a Locale is not necessary because your format does not contain any language- or locale-sensitive parts (is just pure ISO-format). 不需要指定区域设置,因为您的格式不包含任何语言或区域敏感部分(仅为纯ISO格式)。
If you used the excellent Joda-Time library instead of the notoriously troublesome java.util.Date and SimpleTextFormat classes,,you could pass that standard ISO 8601 String directly to a DateTime constructor. 如果您使用了优秀的Joda-Time库而不是臭名昭着的java.util.Date和SimpleTextFormat类,则可以将该标准ISO 8601字符串直接传递给DateTime构造函数。 Joda-Time uses ISO 8601 for its defaults. Joda-Time使用ISO 8601作为默认值。
DateTime dateTime = new DateTime( pubDate );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.