3

I could not find a correctly and clean working solution for my Date which is formatted like this:

2014-06-09T00:01+0200

(9th of June here)

Last I tried was this:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX", Locale.ENGLISH);

This just gives me an unparsable date exception. What do you think I should change?

halfer
  • 19,824
  • 17
  • 99
  • 186
Waylander
  • 825
  • 2
  • 12
  • 34

3 Answers3

3

replace XXX with Z,

String dateTimestr = "2014-06-09T00:01+0200";
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
s.parse(dateTimestr);

to print,

System.out.println(s.format(s.parse(dateTimestr)));

using Java 8,

OffsetDateTime dateTime = OffsetDateTime.parse("2014-06-09T00:01+02:00");
System.out.println(dateTime.toString());

Note that OffsetDateTime.parse would only work if your string is proper ISO8601 date format. If your date is in different format then you have to provide your OffsetDateTime.parse() with a proper formatter using DateTimeFormatter. i.e

OffsetDateTime.parse(yourStringDate, DateTimeFormatter formatter)
Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
2

Use Z instead of XXX or one X

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ", Locale.ENGLISH);

From the documentation:

Z Time zone RFC 822 time zone -0800

X Time zone ISO 8601 time zone -08; -0800; -08:00

Community
  • 1
  • 1
Jens
  • 67,715
  • 15
  • 98
  • 113
0

The problem is XXX requires timezone format with a colon, i.e., 2014-06-09T00:01+02:00

Using Z instead of XXX or using XX (2 X's) should accept format without colon

Be careful with using one X as some have posted because this will disregard the last two digits of the timezone (e.g., 2014-06-09T00:01+02). This could be problematic if working with time zones in some countries like India where the time zone offset is +05:30. Note the following code..

System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX").format(new SimpleDateFormat("yyyy-MM-dd'T'HH:mmX").parse("2014-06-09T00:01+05:30")));

Will print 2014-06-08T14:01-05:00. The :30 in the timezone was lost when using one X. Documentation

Ross
  • 26
  • 2