I have a date string and I want to parse it to normal date use the java Date API,the following is my code:
public static void main(String[] args) {
String date="2010-10-02T12:23:23Z";
String pattern="yyyy-MM-ddThh:mm:ssZ";
SimpleDateFormat sdf=new SimpleDateFormat(pattern);
try {
Date d=sdf.parse(date);
System.out.println(d.getYear());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
However I got an exception: java.lang.IllegalArgumentException: Illegal pattern character 'T'
So I wonder if I have to split the string and parse it manually?
BTW, I have tried to add a single quote character on either side of the T:
String pattern="yyyy-MM-dd'T'hh:mm:ssZ";
It also does not work.
Update for Java 8 and higher
You can now simply do
Instant.parse("2015-04-28T14:23:38.521Z")and get the correct thing now, especially since you should be usingInstantinstead of the brokenjava.util.Datewith the most recent versions of Java.You should be using
DateTimeFormatterinstead ofSimpleDateFormatteras well.Original Answer:
This works with the input with the trailing
Zas demonstrated:Q2597083.java
Produces the following output: