問題描述
我必須在 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.
這篇關于無法解析自定義日期格式.(爪哇)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!