Question

I have a timestamp string 2013-03-01T11:22:18.01Z generated by strftime("%Y:%m:%dT%H:%M:%SZ"), which is in Python.

Now I'm trying to use Java's SimpleDateFormat to parse this timestamp. Lot's of sample code that I found seem to do this:

String DATE_FORMAT = "YYYY-MM-DD'T'hh:mm:ss.ssZ"
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT)
sdf.setLenient(false)
sdf.parse(timestamp) <---- throws ParseException here

However, I get an error dialog that says Unparseable date: "2013-03-01T11:22:18.01Z"

I've been tweaking DATE_FORMAT here and there, trying all sorts of things but I've been stuck on the same roadblock for quite a while now. Looks like I'll need to borrow the power of the stackoverflow community on this.

Was it helpful?

Solution

Other than the yyyy vs YYYY and dd versus DD, the Z is also causing a problem. Your SimpleDateFormat with a pattern like

yyyy-MM-dd'T'HH:mm:ss.ssZ
 |   |  |  | |  |  |  | |
 |   |  |  | |  |  |  | -----timezone (RFC 822 time zone, ex: -0800)
 |   |  |  | |  |  |  -------seconds again (maybe you wanted SS for milliseconds)
 |   |  |  | |  |  ----------seconds (0-59)
 |   |  |  | |  -------------minutes (0-59)
 |   |  |  | ----------------hours (0-23)
 |   |  |  ------------------the character T
 |   |  ---------------------day in month 
 |   ------------------------month in year
 ----------------------------year

But the String you pass, "2013-03-01T11:22:18.01Z", simply has a Z at the end, not a timezone.

If you are actually expecting a Z at the end, then you need to quote it in the format string:

yyyy-MM-dd'T'HH:mm:ss.ss'Z'

just like you did for T. From the javadoc:

Text can be quoted using single quotes (') to avoid interpretation.

OTHER TIPS

1) correct pattern for 2013-03-01T11:22:18.01 is "yyyy-MM-dd'T'HH:mm:ss.SSS" (if .01 is millis)

2) Z timezone in 2013-03-01T11:22:18.01Z cannot be parsed by SimpleDateFormat 'Z' which accepts only -0800 format (RFC 822). Even if you change it to 'z' (General time zone) it still wont parse Z, it should be GMT

see SimmpleDateFormat API.

3) 2013-03-01T11:22:18.01Z looks like very much XSD dateTime format http://www.schemacentral.com/sc/xsd/t-xsd_dateTime.html and can be parse with DatatypeConverter.parseDateTime from java.xml.bind package (Java standard library)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top