Parse Date String in Java [duplicate]

风格不统一 提交于 2019-12-17 17:23:06

问题


I have date in the format "yyyy-MM-dd'T'HH:mm:ss.sssZ". for example the date is "2018-07-17T09:59:51.312Z". I am using the below code to parse the String in Java.

  String date="2018-07-17T09:59:51.312Z";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ");
   Date transactionDateTime = simpleDateFormat.parse(date);

This is giving me "Unparseable date:" Exception. Can anyone please tell me how to do this?


回答1:


You forgot to add ' before the Z - RFC 822 time zone (-0800)

String date = "2018-07-17T09:59:51.312Z";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date transactionDateTime = simpleDateFormat.parse(date);

That will do the work




回答2:


You should consider using the DateTimeFormatter and ZonedDateTime for this example. Date and SimpleDateFormat are old classes, and have been prone to errors and can be problematic; the newer classes mentioned (Java8+) are much more robust.

And change the end of your pattern from ...mm:ss.sssZ to ...mm:ss.SSSz.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(date, formatter);
System.out.println(formatter.format(zonedDateTime));

You could also use OffsetDateTime or Instant (credit: Ole V.V) which will parse for you, giving the same output:

System.out.println(OffsetDateTime.parse("2018-07-17T09:59:51.312Z"));
System.out.println(Instant.parse("2018-07-17T09:59:51.312Z"));

Output:

2018-07-17T09:59:51.312Z



来源:https://stackoverflow.com/questions/52480189/parse-date-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!