java.sql.Timestamp to String with microsecond precision

和自甴很熟 提交于 2020-01-02 08:46:41

问题


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.

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.


回答1:


You can use the getNanos()-methode of Timestamp.

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());


来源:https://stackoverflow.com/questions/20748449/java-sql-timestamp-to-string-with-microsecond-precision

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!