Java.sql.Timestamp如何以微秒精度转换为字符串

3
我正在从数据库中读取时间戳列,并将其转换为java.sql.Timestamp对象。然后,我想将时间戳的值转换为一个String对象,但保留微秒精度。调用toString()方法可以接近,但似乎会丢失微秒中的尾随零。如果时间戳以非零数字结尾,则一切正常。
示例:
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

我真的想要打印出2005-02-25 11:50:11.579410。


S 表示毫秒,而不是微秒。 - Boris the Spider
同意。我只是放了一个示例来展示它的行为。 - Mensur
为什么需要微秒级精度? - ashes999
1
我正在不同的数据库系统之间复制数据,时间戳精度必须得到保留。 - Mensur
1个回答

5
您可以使用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());

1
最好使用String.format或者更好的MessageFormat而不是自定义追加代码。 - Boris the Spider

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接