5

I have the following code:

  String ModifiedDate = "1993-06-08T18:27:02.000Z" ;  
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
  Date ModDate = sdf.parse(ModifiedDate);

I am getting the following exception even though my date format is fine...

java.text.ParseException: Unparseable date: "1993-06-08T18:27:02.000Z"
at java.text.DateFormat.parse(DateFormat.java:337)
demongolem
  • 9,148
  • 36
  • 86
  • 104
user2133404
  • 1,686
  • 4
  • 30
  • 56
  • Try single quote the 'Z' SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); – gtgaxiola Jun 12 '14 at 19:27
  • Do you want to use ISODateTimeFormat (which is in joda)? Might be better for that ISO8601 standard. See http://stackoverflow.com/questions/5393847/how-can-i-convert-a-timestamp-from-yyyy-mm-ddthhmmsssssz-format-to-mm-dd-yyyy – demongolem Jun 12 '14 at 19:28

2 Answers2

10

The Z pattern latter indicates an RFC 822 time zone. Your string

String ModifiedDate = "1993-06-08T18:27:02.000Z" ;  

does not contain such a time zone. It contains a Z literally.

You'll want a date pattern, that similarly to the literal T, has a literal Z.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

If you meant for Z to indicate Zulu time, add that as a timezone when constructing the SimpleDateFormat

sdf.setTimeZone(TimeZone.getTimeZone("Zulu"));;
Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
  • I will add change the `ModifiedDate` to take a time zone difference such as '2001-07-04T12:08:56.235-0700' [SampleDateFormat Examples section](http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) – gtgaxiola Jun 12 '14 at 19:32
  • @gtgaxiola Absolutely, if OP can change their input string, it might be easier to do that. – Sotirios Delimanolis Jun 12 '14 at 19:33
0

The answer by Sotirios Delimanolis is correct. The Z means Zulu time, a zero offset from UTC (+00:00). In other words, not adjusted to any time zone.

Joda-Time

FYI, the Joda-Time library make this work much easier, as does the new java.time package in Java 8.

The format you are using is defined by the ISO 8601 standard. Joda-Time and java.time both parse & generate ISO 8601 strings by default.

A DateTime in Joda-Time knows its own assigned time zone. So as part of the process of parsing, specify a time zone to adjust.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( "1993-06-08T18:27:02.000Z", timeZone );
String output = dateTime.toString();

You can keep the DateTime object in Universal Time if desired.

DateTime dateTime = new DateTime( "1993-06-08T18:27:02.000Z", DateTimeZone.UTC );

When required by other classes, you can generate a java.util.Date object.

java.util.Date date = dateTime.toDate();
Community
  • 1
  • 1
Basil Bourque
  • 262,936
  • 84
  • 758
  • 1,028