0

What is the correct form for parse this date?: 2015-05-29T00:00:00+02:00

DateFormat format = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date data = format.parse(dataValue);
michele
  • 26,348
  • 30
  • 111
  • 168

2 Answers2

3

Try with

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

Notice that

  • MM represents months, while mm represents minutes.
  • if you want to have 24h format use HH, hh is for 12h format
  • XXX represents time zone in format like -08:00
  • to add literal like T in format you need to surround it with single quotes ' like 'T'
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Thanks it works, can I ask you how can I do to change the format output in "yyyy-MM-dd" ? – michele Jun 04 '15 at 22:43
  • If you have data as string in format `yyyy-MM-dd'T'HH:mm:ssXXX` and you want to convert it to format `yyyy-MM-dd` them I would say that simplest way would be using substring to pick this `yyyy-MM-dd` part. But if you for instance would like to convert it to something like `dd/MM/yyyy` then you would need to create another date formatter and simply `format` `Date` returned by original formatter. So your code can be like `String newFormat = newFormatter.format(oldFormatter.parse(stringDate))`. – Pshemo Jun 04 '15 at 22:48
0

java.time

The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Since the modern date-time API is based on ISO 8601 standards, you are not required to use a DateTimeFormatter object explicitly to parse a date-time string conforming to the ISO 8601 standards. Your date-time string contains timezone offset string (+02:00) and therefore, the most appropriate type to be used to parse it is OffsetDateTime.

Demo:

import java.time.OffsetDateTime;

public class Main {
    public static void main(String args[]) {
        OffsetDateTime odt = OffsetDateTime.parse("2015-05-29T00:00:00+02:00");
        System.out.println(odt);
    }
}

Output:

2015-05-29T00:00+02:00

For whatsoever reason, if you need an instance of java.util.Date from this object of OffsetDateTime, you can do so as follows:

Date date = Date.from(odt.toInstant());

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