1

Keep getting a ParseException when I try to parse a ISO 8601 formatted String into a Java Date type.

String myDateString = "2014-07-04T22:59:36Z";  
TimeZone timeZone = TimeZone.getTimeZone("UTC");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US);
dateFormat.setTimeZone(timeZone);
Date formattedDate = dateFormat.parse(myDateString);

Keeps returning a ParseException:

Unparseable date: "2014-07-04T22:59:36Z"

What am I possibly doing wrong?

Andre Perez
  • 29
  • 1
  • 5
  • You should use `X` (unquoted) rather than `'Z'`. And you need the `:ss` for seconds -- `"yyyy-MM-dd'T'HH:mm:ssX"`. – Hot Licks Aug 28 '14 at 00:53
  • possible duplicate of [Trouble parsing a certain Date format, I keep getting ParseException](http://stackoverflow.com/questions/31090946/trouble-parsing-a-certain-date-format-i-keep-getting-parseexception) – Basil Bourque Jun 28 '15 at 03:47

2 Answers2

0

You are missing the seconds in your date format:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
Justin
  • 1,356
  • 2
  • 9
  • 16
0

tl;dr

For Java 6 & 7, add the ThreeTen-Backport library to your project. For Java 8 and later, java.time is built-in.

Instant.parse( "2014-07-04T22:59:36Z" )

java.time

The modern way is with the java.time classes that supplant the troublesome old legacy date-time classes such as SimpleDateFormat, Date, and Calendar.

While built into Java 8 and later, a back-port to Java 6 and Java 7 is available. (see below)

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern. The Instant class can directly parse your input string.

Instant instant = Instant.parse( "2014-07-04T22:59:36Z" );

To generate a String in standard ISO 8601 format, simply call toString.

String output = instant.toString();

2014-07-04T22:59:36Z


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154