Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat with Offset not recognized

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)
like image 495
JavaDeveloper Avatar asked Jun 21 '26 23:06

JavaDeveloper


2 Answers

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

like image 130
nostromo Avatar answered Jun 25 '26 23:06

nostromo


java.time

In 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.

Solution using java.time API

Your 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 OffsetDateTime from a text string such as 2007-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:

  1. For some reason, if you need an instance of java.util.Date, you can obtain it using odt from the above code as Date.from(odt.toInstant()).
  2. You can also parse your date-time string into an 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.

like image 26
Arvind Kumar Avinash Avatar answered Jun 25 '26 22:06

Arvind Kumar Avinash