问题
I need to parse a string to date in java. My string has the following format:
2014-09-17T12:00:44.0000000Z
but java throws the following exception when trying to parse such format... java.lang.IllegalArgumentException: Illegal pattern character 'T'
.
Any ideas on how to parse that?
Thank you!
回答1:
Given your input of 2014-09-17T12:00:44.0000000Z
, it is not sufficient to escape the letter T
only. You also have to handle the trailing Z
. But be aware, this Z
is NOT a literal, but has the meaning of UTC+00:00
timezone offset according to ISO-8601-standard
. So escaping Z
is NOT correct.
SimpleDateFormat
handles this special char Z
by pattern symbol X
. So the final solution looks like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX");
Date d = sdf.parse("2014-09-17T12:00:44.0000000Z");
System.out.println(d); // output: Wed Sep 17 14:00:44 CEST 2014
Note that the different clock time is right for timezone CEST
(toString()
uses system timezone), and that the result is equivalent to UTC-time 12:00:44
. Furthermore, I had to insert seven symbols S in order to correctly process your input which pretends to have precision down to 100ns
(although Java pre 8 can only process milliseconds).
回答2:
You have to escape the 'T' character:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parse = format.parse("2014-09-17T12:00:44.0000000Z");
Using Answer to: What is this date format? 2011-08-12T20:17:46.384Z
回答3:
Try this.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateClass {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date d = sdf.parse("2014-09-17T12:00:44.0000000Z");
System.out.println(d); //output Wed Sep 17 12:00:44 IST 2014
}
}
来源:https://stackoverflow.com/questions/26398657/parsing-string-to-date-illegal-pattern-character-t