I needed to parse below Date coming from a web service.
2014-09-16T18:05:00.000-05:00
So I tried to created SimpleDateFormat object
SimpleDateFormat simpleDateFormat = new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
JavaDocs has below example and format given in the table that matches with my date format.
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
However, I am getting below exception. I use jdk 1.7.0_55. Is there something I am missing ?
Caused by: java.lang.IllegalArgumentException: Illegal pattern character 'X'
at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:768)
at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:575)
at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:500)
at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:475)
Check the version of Java you're using. I bet you're actually using 6.
$ java -version
java version "1.6.0_65"
The XXX format was added in 7. Compare:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
java.timeIn March 2014, Java 8 introduced the modern, java.time date-time API which supplanted the error-prone legacy java.util date-time API. Any new code should use the java.time API.
java.time APIYour date-time string, 2014-09-16T18:05:00.000-05:00 is in ISO 8601 format, which is also the default format used by java.time API. Below is an excerpt from the OffsetDateTime documentation:
Obtains an instance of
OffsetDateTimefrom a text string such as2007-12-03T10:15:30+01:00.
Therefore, you do not need to use a DateTimeFormatter explicitly to parse your date-time string.
Demo:
public class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.parse("2014-09-16T18:05:00.000-05:00");
System.out.println(odt);
}
}
Output:
2014-09-16T18:05-05:00
Try it on Ideone
Notes:
java.util.Date, you can obtain it using odt from the above code as Date.from(odt.toInstant()).Instant or a ZonedDateTime as Instant.parse("2014-09-16T18:05:00.000-05:00") and ZonedDateTime.parse("2014-09-16T18:05:00.000-05:00").Learn more about the modern Date-Time API from Trail: Date Time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With