问题
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