Question

The date format of the xml output of the svn log command is like the following.

2014-04-24T08:51:58.213757Z

I tried to parse this to a util.Date object using SimpleDateFormat with the following String.

yyyy-MM-ddTHH:mm:ss.SSSSSSZ

Complete method

protected Date formatDate(String dateString) {
        //2014-04-24T08:51:58.213757Z

        DateFormat format = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss.SSS");
        format.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));
        Date date = null;
        int lengthToParse = "yyyy-MM-ddTHH:mm:ss.SSS".length();

        try {
            date = format.parse(dateString.substring(0, lengthToParse));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

However this gives an error as follows.

java.lang.IllegalArgumentException: Illegal pattern character 'T'
Was it helpful?

Solution

You need to quote the T because you want it to match literally. You also want X as the format specifier for the time zone, not Z:

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

Or you could specify the time zone as UTC, and quote the Z as well.

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

However, you may still have problems because that's going to interpret 213757 as a number of milliseconds, not microseconds.

I'm not sure there's a clean way of parsing microseconds with SimpleDateFormat - you're probably best off just parsing a substring:

String text = "2014-04-24T08:51:58.213567Z";
// You could just hard code the length, but this feels easier to read
String trimmed = text.substring(0, "yyyy-MM-ddTHH:mm:ss.SSS".length());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
Date date = format.parse(trimmed);

Note that you definitely want Etc/UTC as the time zone, because the input is in UTC... that's what the 'Z' means at the end of the string.

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