以下代码片段显示SimpleDateFormat在毫秒内正常工作,但与额外的小数位不一致。 (它来自我的数据源,额外的数字始终为零。)
// working as expected with milliseconds
try {
String dateString = "03:15:28.142";
String format = "hh:mm:ss.SSS";
DateFormat formatter = new SimpleDateFormat(format);
Date date = new Date();
System.out.println(formatter.format(date));
date = formatter.parse(dateString);
System.out.println(date + "\t" + date.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// not working as expected with one extra decimal place
try {
String dateString = "03:15:28.1420";
String format = "hh:mm:ss.SSS0";
DateFormat formatter = new SimpleDateFormat(format);
Date date = new Date();
// date to string works as expected
System.out.println(formatter.format(date));
date = formatter.parse(dateString);
// string to date doesn't work at all
System.out.println(date + "\t" + date.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
输出
09:23:07.545
Thu Jan 01 03:15:28 EST 1970 29728142
09:23:07.5490
java.text.ParseException: Unparseable date: "03:15:28.1420"
我可以将日期转换为格式化的字符串,但我无法将字符串转换为日期。 我有一个解决方法,所以这是一个“很高兴知道” - 但明显的不一致困扰着我。
答案 0 :(得分:1)
您的格式可能存在错误,其中包含额外的 0 。
试着写下格式:
String format = "hh:mm:ss.SSS";