Mike Flynn Mike Flynn - 1 year ago 84
Java Question

Java Can't Parse UTC Date with SimpleDateFormat

Why am I getting an error below? It happens only with some dates.

Helper.getDate("2014-01-09T17:10:14Z", "dd-MM-yyyy");

public static Date getDate(String date, String format) {
DateFormat df = new SimpleDateFormat(format);

try {
return df.parse(date);
} catch (ParseException e) {
log.error("getDate", e);

return null;

Answer Source

This date:


has a format of "yyyy-MM-dd'T'HH:mm:ss'Z'"

(or in Java 7 "yyyy-MM-dd'T'HH:mm:ssX")

So of course it will be impossible to parse it with a format dd-MM-yyyy.

The formatting string needs to be compatible with the input!

(Note I gave a literal Z, this is back compatible. Java 7 actually understands ISO8601 and you could use an X there to have it actually be parsed.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download