Parse Date String in Java [duplicate]

别等时光非礼了梦想. 提交于 2019-11-28 14:23:05

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

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

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