使用SimpleDateFormat解析svn log -xml日期输出 [英] Parse svn log -xml date output using SimpleDateFormat

查看:237
本文介绍了使用SimpleDateFormat解析svn log -xml日期输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

svn log命令的xml输出的日期格式如下.

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

2014-04-24T08:51:58.213757Z

我尝试使用带有以下字符串的SimpleDateFormat将其解析为util.Date对象.

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

yyyy-MM-ddTHH:mm:ss.SSSSSSZ

完整方法

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;
    }

但这会产生如下错误.

java.lang.IllegalArgumentException: Illegal pattern character 'T'

推荐答案

您需要引用T,因为您希望它在字面上匹配.您还希望X作为时区的格式说明符,而不是Z:

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

或者您可以将时区指定为UTC,并同时引用Z.

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

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

但是,您可能仍然会遇到问题,因为这会将213757解释为毫秒数,而不是微秒数.

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

我不确定是否有一种使用SimpleDateFormat解析微秒的干净方法-您最好只解析一个子字符串:

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);

请注意,您肯定要使用Etc/UTC作为时区,因为 input 以UTC表示...这就是字符串末尾的"Z"的含义.

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.

这篇关于使用SimpleDateFormat解析svn log -xml日期输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆