Pergunta

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

Foi útil?

Solução 2

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

Outras dicas

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.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top