在Android中将“2018-02-02T06:54:57.744Z”字符串转换为日期

时间:2018-02-03 07:11:53

标签: java android iso8601

基本上我的日期字符串是ISO-8601日期字符串,所以我搜索了将ISO-8601日期字符串转换为日期,但解决方案很冗长。以下是详细信息。

我有一个字符串2018-02-02T06:54:57.744Z想要将其转换为日期,但我收到错误:

java.text.ParseException: Unparseable date: "2018-02-02T06:54:57.744Z"

我正在使用以下技术来做到这一点,但没有成功:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
        parser.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date parsed = parser.parse(utcDateString);
        return parsed;

我还使用SimpleDateFormat的以下模式,但没有成功:

yyyy-MM-dd'T'HH:mm:ss.SSSZ
yyyy-MM-dd HH:mm:ss.S
yyyy-MM-dd'T'HH:mm:ssX
yyyy-MM-dd'T'HH:mm'Z'

解决这个问题的任何方法。

3 个答案:

答案 0 :(得分:7)

Z是时区。您必须在日期字符串末尾添加时区,或者只是将其从格式yyyy-MM-dd'T'HH:mm:ss

中删除

带有时区的正确日期字符串如下所示:2018-02-02T06:54:57.744+0200

答案 1 :(得分:6)

试试这个

SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");

Date d = null;
try 
{
   d = input.parse("2018-02-02T06:54:57.744Z");
} 
catch (ParseException e) 
{
   e.printStackTrace();
}
String formatted = output.format(d);
Log.i("DATE", "" + formatted);

<强>输出

enter image description here

答案 2 :(得分:3)

tl;dr

Instant.parse( “2018-02-02T06:54:57.744Z” ) 

java.time

The modern approach uses java.time classes.

Instant is the replacement for java.util.Date, representing a moment on the timeline in UTC.

Your input string happens to comply with the ISO 8601 standard. The java.time classes use standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

Instant instant = Instant.parse( “2018-02-02T06:54:57.744Z” ) ;

Best to avoid the troublesome java.util.Date class entirely. But if you insist, convert using new methods added to the old classes.

Date d = Date.from( instant ) ;

For earlier Android, see the ThreeTen-Backport and ThreeTenABP projects.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?