user007
user007

Reputation: 101

How to create proper DateTimeFormatter Pattern

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.

Upvotes: 3

Views: 18312

Answers (4)

Micahel
Micahel

Reputation: 1

DateTimeFormatter from "yyyy-MM-dd'T'HH:mm:ssX" worked for me.

Upvotes: 0

Stefan Haberl
Stefan Haberl

Reputation: 10559

Late to the party, but you have to include some timezone information in your timestamp string. Otherwise it would be undefined from which timezone you'll want to substract your offset of five hours.

Assuming that you'll want to parse a timestamp which is 5 hours behind UTC, your string should read

2016-07-22T00:00:00.000Z-05:00

Note the 'Z' before the -05:00 part, which is short for "UTC"

Upvotes: 0

Matt M
Matt M

Reputation: 36

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.

Upvotes: 2

tnas
tnas

Reputation: 511

The API's javadoc describe the patterns: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

I've tested this code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = new Date();
System.out.println(sdf.format(date));

The output was:

2016-08-22T18:34:26.604-03:00

Upvotes: -1

Related Questions