无法解析自定义日期格式.(爪哇)

2022-01-12 00:00:00 datetime parsing formatting java

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

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

@Test公共无效 testDateFormat() 抛出 ParseException {DateFormat 格式 = 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 字段后,解析器仍会查找000"子字符串并因异常而失败,因为您已到达输入字符串的末尾,而没有满足模式的要求.

由于 SimpleDateFormat 中没有 µs 值的模式,因此您必须编写自己的包装器来去除最后三个 0 字符的输入字符串,然后再将其提供给 SimpleDateFormat.

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.

相关文章