自定义日期格式无法解析。 (Java) [英] Custom date format cannot be parsed. (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屋!