6

I want to define a pattern for the Java SimpleDaterFormat to parse existing strings.

The existing dates look like this: 2011-05-02T13:40:00+02:00.

I tried with different patterns, but I got ParseExceptions. The problem seems to be the timezone format.

Printing the pattern in Java:

  • yyyy-MM-dd'T'HH:mm:ssZ
    • 2012-03-14T15:40:44+0100
  • yyyy-MM-dd'T'HH:mm:ssz
    • 2012-03-14T15:41:58MEZ

But how can I get

  • ???
    • 2011-05-02T13:40:00+02:00

I'm using Java 6, not Java 7.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
cuh
  • 3,723
  • 4
  • 30
  • 47

2 Answers2

6

If you can use Java 7 or newer, you can use the XXX pattern to get the timezone to look like +02:00:

yyyy-MM-dd'T'HH:mm:ssXXX

Otherwise you might have to manipulate the date string to remove the colon from the timezone before parsing it.

matts
  • 6,738
  • 1
  • 33
  • 50
  • Thx. Yes the support for ISO 8601 Time zone is realized with Java 7, but my application runs under Java 1.6. – cuh Mar 14 '12 at 14:59
  • 1
    Maybe you can just remove the colon before passing it to the formatter then? I think this regex should only have an effect if the colon is there: dateString.replaceFirst("(\\d\\d):(\\d\\d)$", "$1$2") – matts Mar 14 '12 at 15:08
  • I can not modify the string first. I use an tool to import a set of data and can only define a pattern. – cuh Mar 14 '12 at 15:15
  • 2
    Above comment from @matts works for me where I parse a value of ISO8601 date pattern in Android which doesn't support Java 7. Simple and clear solution. – Ramanathan Aug 26 '14 at 04:07
1

I know it's a bit old question, but someone else might benefit from my hint. You can use JodaTime. As library documentation stands:

Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with a colon, 'ZZZ' or more outputs the zone id.

You can use it as well with java 6. You have more examples in this question

Community
  • 1
  • 1
Augustin Ghauratto
  • 1,420
  • 1
  • 19
  • 21