java.sql.Timestamp to String 微秒精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20748449/
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
java.sql.Timestamp to String with microsecond precision
提问by Mensur
I am reading a timestamp column from the database into a java.sql.Timestamp object. Then I would like to convert the value of the timestamp to a String object but keep the microsecond precision. Calling toString() method gets me close but it seems to lose trailing zeros in the microsecond. If the timestamp ends in a non-zero number, everything is fine.
我正在将数据库中的时间戳列读入 java.sql.Timestamp 对象。然后我想将时间戳的值转换为 String 对象,但保持微秒精度。调用 toString() 方法让我很接近,但它似乎在微秒内丢失了尾随零。如果时间戳以非零数字结尾,则一切正常。
Sample:
样本:
SimpleDateFormat outDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String s = "2005-02-25 11:50:11.579410";
java.sql.Timestamp ts = java.sql.Timestamp.valueOf(s);
String out = ts.toString(); // This returns 2005-02-25 11:50:11.57941
out = outDateFormat.format(ts); // This returns 2005-02-25 11:50:11.000579
I am really looking to print 2005-02-25 11:50:11.579410.
我真的很想打印 2005-02-25 11:50:11.579410。
采纳答案by Meno Hochschild
You can use the getNanos()-methode of Timestamp.
您可以使用时间戳的 getNanos() 方法。
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.");
String s = "2005-02-25 11:50:11.579410";
java.sql.Timestamp ts = java.sql.Timestamp.valueOf(s);
int microFraction = ts.getNanos() / 1000;
StringBuilder sb = new StringBuilder(fmt.format(ts));
String tail = String.valueOf(microFraction);
for (int i = 0; i < 6 - tail.length(); i++) {
sb.append('0');
}
sb.append(tail);
System.out.println(sb.toString());