【发布时间】:2014-12-17 20:16:24
【问题描述】:
我在文本文件的字符串中有这样一个日期:String string = 2014-10-03 00:58:59.765
所以我是这样解析的:
Date timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.parse(string);
但是,一些时间戳的毫秒数少于 3 位,我得到一个 ParseException 试图在它们上使用相同的 SimpleDateFormat。编辑:当毫秒为 000 时发生。例如:java.text.ParseException: Unparseable date: "2014-10-03 00:59:49"
这是我的解决方法:
if (string.length() == 23) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.parse(string);
} else if (string.length() == 22) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS")
.parse(string);
} else if string.length() == 21) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS")
.parse(string);
} else if (string.length() == 19) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(string);
}
难道没有更好的方法吗?
【问题讨论】:
-
2014-10-03 00:58:59.7, 2014-10-03 00:58:59.71, 2014-10-03 00:58:59.716 应该与 yyyy-MM-dd HH 一起使用:毫米:ss.SSS。你能粘贴你得到解析异常的字符串吗?
-
是的,在毫秒为 000 的情况下:java.text.ParseException: Unparseable date: "2014-10-03 00:59:49"
标签: java parsing date timestamp simpledateformat