自定义日期格式无法解析。 (Java) [英] Custom date format cannot be parsed. (Java)

查看:283
本文介绍了自定义日期格式无法解析。 (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在Java中使用自定义日期格式。它包含微秒,尽管Java不提供对微秒的支持。因为这样,我填充了时间模式为零,这在格式化时工作正常,但是我无法使用该模式解析日期字符串。



是否有简单的解决方法或必须我自己处理微秒(使用String函数)?

  @Test 
public void testDateFormat()throws ParseException {
DateFormat format = new SimpleDateFormat(yyyy-MM-dd-HH.mm.ss.SSS000);
String theDate = format.format(new Date());
//这将失败:
format.parse(theDate);
}




java.text.ParseException:不可抛出的日期: 2010-01-25-12.40.35.769000



解决方案

你的问题是, SimpleDateFormat中使用的不同之处在于它是否用作解析器或格式化程序,具有不同的含义。作为格式化程序,您的模式将执行预期的操作,输出将以毫秒值结尾,格式为三位数字,后跟三个0个字符,例如:



2010-01- 25-14.17.47.307000



作为解析器,SSS模式将匹配任意位数,并将上述示例解析为307000 ms。解析ms字段后,解析器仍然会查找一个000子字符串并失败并发生异常,因为您已经到达输入字符串的末尾,而不满足模式的要求。



由于在SimpleDateFormat中没有一个μs值的模式,所以您必须编写自己的包装器,以便在将其输入到SimpleDateFormat之前,删除最后三个0个字符的输入字符串。


I have to use a custom date format in Java. It contains microseconds although Java doesn't provide support for microseconds. Because of that I filled the time pattern with zeroes, which work fine when formatting, but I cannot parse date-strings with that pattern.

Is there a simple workaround or must I handle microseconds on my own (with String functions)?

@Test
public void testDateFormat() throws ParseException {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS000");
    String theDate = format.format(new Date());
    // this will fail:
    format.parse(theDate);
}

java.text.ParseException: Unparseable date: "2010-01-25-12.40.35.769000"

解决方案

Your problem is that the pattern used in SimpleDateFormat unfortunately have different meanings depending on whether it is used as a parser or as a formatter. As a formatter, your pattern does what is expected, the output will end with the millisecond value formatted as three digits followed by three 0 characters, e.g:

2010-01-25-14.17.47.307000

Used as a parser, the "SSS" pattern will however match an arbitrary number of digits and parse the above example as 307000 ms. After having parsed the ms field, the parser will still look for a "000" substring and fail with an exception, since you've reached the end of the input string, without fulfilling the requirements of the pattern.

Since there is no pattern for a µs value in SimpleDateFormat, you will have to write your own wrapper to strip the input string for the last three 0 characters, before feeding it to SimpleDateFormat.

这篇关于自定义日期格式无法解析。 (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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