java SimpleDateFormat to Timestamp 使用 getTime() 方法失去精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17791762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SimpleDateFormat to Timestamp loses precision with getTime() method
提问by deanmau5
I've got a method to parse a String (yyyy-MM-dd HH:mm:ss.SSS) to a Date object using SimpleDateFormat.
我有一种方法可以使用 SimpleDateFormat 将字符串 (yyyy-MM-dd HH:mm:ss.SSS) 解析为 Date 对象。
public static Timestamp convertToTimestamp(String stringToFormat) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
Date date = dateFormat.parse(stringToFormat);
Timestamp tstamp = new Timestamp(date.getTime());
return tstamp;
}
catch (ParseException e) {
return null;
}
}
However, when the Milliseconds end in 0, eg "2013-07-07 19:15:00.000", when I do the following to assign it to a Timestamp object:
但是,当毫秒以 0 结尾时,例如“2013-07-07 19:15:00.000”,当我执行以下操作将其分配给 Timestamp 对象时:
Timestamp tstamp = new Timestamp(date.getTime());
the output is the following 2013-07-07 19:15:00.0
输出如下2013-07-07 19:15:00.0
Is there any way to keep my precision of three decimal places on the Milliseconds? I realise I could probably do some sort of length check and manually add on 0's, but a more efficient, standard way of keeping this precision would be preferred
有什么办法可以让我的毫秒精度保持小数点后三位?我意识到我可能会进行某种长度检查并手动添加 0,但是最好采用更有效的标准方法来保持这种精度
回答by assylias
The precision is not lost: the trailing zeros are simply truncated.
精度不会丢失:尾随零被简单地截断。
You can verify it with:
您可以通过以下方式进行验证:
Date dt = new Date();
dt.setTime(123); //123 milliseconds
Timestamp tstamp = new Timestamp(dt.getTime());
System.out.println("tstamp = " + tstamp);
dt.setTime(0); //0 milliseconds => truncated
tstamp = new Timestamp(dt.getTime());
System.out.println("tstamp = " + tstamp);
which prints:
打印:
tstamp = 1970-01-01 01:00:00.123
tstamp = 1970-01-01 01:00:00.0