我在 java 中有两个日期,格式为 yyyy-MM-dd HH:mm:ss.SSS。我需要做一个简单的算术运算。我的代码是:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String out = resu.getString(3);
Date dateOut = formatter.parse(out);
String in = resu.getString(4);
Date dateIn = formatter.parse(in);
long msDiff = dateOut.getTime() - dateIn.getTime();
如果两个日期均为 3 毫秒,则此操作正常,例如:
dateIn = 2015-10-14 16:32:20.037
dateOut = 2015-10-14 16:32:20.093
但是当一个日期有一位或两位数字而不是在右边用零完成值时,它会在左边完成,这当然会改变操作的结果。示例。
dateIn = 2015-10-14 16:32:20.05
dateOut = 2015-10-14 16:32:20.067
dateOut - dateIn = 062 //this is wrong, it should be 067 - 050 = 17.
我做错了什么?
我没有找到好的解决方案,所以我做了一个工作正常的解决方法。它检查毫秒数并始终返回三。
public static String completeDate (String date) {
String digits = date.substring(date.indexOf("."));
int cantDigits = digits.length();
while (cantDigits < 4){
digits = digits + "0";
cantDigits = digits.length();
}
String newDate = date.substring(0,date.indexOf(".")) + digits;
return newDate;
}
最佳答案
这两个日期在技术上具有不同的模式,因为小数点后的位数不同。来自documentation of SimpleDateFormat
:
Pattern letters are usually repeated, as their number determines the exact presentation:
...
For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
鉴于此,日期 2015-10-14 16:32:20.05
被解释为 2015-10-14 16:32:20.005
(小数被填充零表示三位数字),因此相差 62 毫秒。您应该为这两个日期使用不同的格式化程序,或者很可能应该查看这两个值的插入方式以及它们具有不同格式的原因。
关于java - java.util.Date 中的毫秒没有得到很好的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135014/