0

I have the following string in Java:

2011-12-21T20:27:32-08:00

Can any one tell me how do I store this string by converting it to date?

I need to store it in a MySQL column declared as TimeStamp.

I've tried the following but it does not work:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz").parse("2011-12-21T20:27:32-08:00");

It gives below error:

Exception in thread "main" java.text.ParseException: Unparseable date: "2011-12-21T20:27:32-08:00" –

Any help is much appreciated.

Freephone Panwal
  • 1,547
  • 4
  • 21
  • 39

2 Answers2

3

According to the documentation, z expects timezone indicators in a different format than the one in your string, but you can use X instead, which supports them. So (change is at the end of the format string):

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX").parse("2011-12-21T20:27:32-08:00");

From the docs:

Letter  Date or Time Component   Presentation         Examples
------  -----------------------  -------------------  -------------------------------------
z       Time zone                General time zone    Pacific Standard Time; PST; GMT-08:00
Z       Time zone                RFC 822 time zone    -0800
X       Time zone                ISO 8601 time zone   -08; -0800; -08:00

Daniel Kaplan points out in the comments that X seems to be new. You might need to pre-process the string a bit to remove the colon and use Z (capital, not z; the second in the list above) instead, depending on your environment.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Just be aware `X` is new. [At least it's not in the documentation of JDK6](http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) – Daniel Kaplan Jan 09 '13 at 02:02
  • I'm not clear. X seems to be working for me. What would be the impact if I deploy my code to production with X? – Freephone Panwal Jan 09 '13 at 02:05
  • 1
    @FreephonePanwal What's the version of your JDK and what's the version of your JDK on production? Type `java -version` to find out. If they're both 1.7 it should be fine. – Daniel Kaplan Jan 09 '13 at 02:06
  • They're 1.7 & I should compile with same version i.e. 1.7 as Production before deployment, right? – Freephone Panwal Jan 09 '13 at 02:13
  • @FreephonePanwal: Yup, as long as you're using JDK 1.7+ and the JRE it'll be running on is 1.7+, `X` should work. – T.J. Crowder Jan 09 '13 at 02:14
0

You should have a look at this question: Java SimpleDateFormat for time zone with a colon seperator?. The first answer may be helpful.

Community
  • 1
  • 1