问题
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