How to create proper DateTimeFormatter Pattern

user007 picture user007 · Aug 22, 2016 · Viewed 11.6k times · Source

I am trying to create a DateTimeFormatter object with a pattern to fit this expression of time: 2016-07-22T00:00:00.000-05:00. I am trying to create a DateTime object using the DateTimeFormatter class with the above input string.

I have tried many different versions of the below expression but am currently getting stuck at the timezone piece "-05:00" where I'm getting the error on my junit test case:

java.lang.IllegalArgumentException: Invalid format: "2016-07-22T00:00:00.000-05:00" is malformed at "-05:00"

The current format pattern that I am using is:

yyyy-MM-dd'T'HH:mm:ss.SSSZ

I have also tried:

yyyy-MM-dd'T'HH:mm:ss.SSSTZD
yyyy-MM-dd'T'HH:mm:ss.SSSZZZ
yyyy-MM-dd'T'HH:mm:ss.SSSz
yyyy-MM-dd'T'HH:mm:ss.SSSzzz
yyyy-MM-dd'T'HH:mm:ss.SSS'TZD'

I am running on Java 7 so I am not sure if that is causing an issue as well.

Answer

Matt M picture Matt M · Aug 23, 2016

In order to achieve what you wish, you can utilize the static method "ofPattern" in the DateTimeFormatter class. This method returns a DateTimeFormatter object.

And as shown by tnas, you could use the following date and time format string:

"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"

DateTimeFormatter test = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

I tested the code and it compiles.