Parse svn log -xml date output using SimpleDateFormat

↘锁芯ラ 提交于 2019-12-14 02:15:15

问题


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'

回答1:


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.



来源:https://stackoverflow.com/questions/23579835/parse-svn-log-xml-date-output-using-simpledateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!