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.
tl;dr
ISO 8601
That format is defined by the ISO 8601 standard for date-time string formats.
Both:
…use ISO 8601 formats by default for parsing and generating strings.
You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.
java.time
Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Convert to the old class.
Time Zone
If needed, you can assign a time zone.
Convert.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
Here is some example code in Joda-Time 2.8.
Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.
Time Zone
If needed, you can assign a time zone.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.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 usingInstant
instead of the brokenjava.util.Date
with the most recent versions of Java.You should be using
DateTimeFormatter
instead ofSimpleDateFormatter
as well.Original Answer:
This works with the input with the trailing
Z
as demonstrated:Q2597083.java
Produces the following output: