2

I'm trying to parse this String

2014-04-04T14:28:38+02:00

It should be ISO 8601 format. But i can't parse it to a correct Date. I've tried the following:

   String example = "2014-04-04T14:28:38+02:00"
   public final static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz")
   Date tempDate = df.parse(example)

But I get always the message "unparseable Date" I can not change the example because it's a value from a webservice.

Could it be there is a probleme with "+02:00" instead of "+0200" ?

Thanks a lot

yorah
  • 2,653
  • 14
  • 24
CollinG
  • 67
  • 3
  • 11
  • For new readers to the question I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `OffsetDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 01 '21 at 08:17

3 Answers3

2

java.time

The modern date-time API is based on ISO 8601 and thus, you do not need to use a parser (e.g. DateTimeFormatter) explicitly in order to parse the given date-time string as it is already in ISO 8601 format.

Demo:

import java.time.OffsetDateTime;
import java.util.Date;

public class Main {
    public static void main(String args[]) {
        OffsetDateTime odt = OffsetDateTime.parse("2014-04-04T14:28:38+02:00");
        System.out.println(odt);

        // In case you need java.util.Date
        Date date = Date.from(odt.toInstant());
        // ...
    }
}

Output:

2014-04-04T14:28:38+02:00

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Starting from Java7, to handle +02:00, you can use the following format:

"yyyy-MM-dd'T'hh:mm:ssXXX"

This can be seen in the SimpleDateFormat documentation

yorah
  • 2,653
  • 14
  • 24
0

The ISO8601 date format can be most easily parsed using Joda Time which can be use as a library.

It seems that a form of Joda Time got into Java 8 as JSR310 but I have not worked with it.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213