如何打印秒数值最多6位精度的时间
我在列中的值是timestamp类型。 让我说我有一个价值2007-05-04 08:48:40.969774
现在,当尝试从数据库中获取值并将此时间戳值返回给函数时,我应该使用什么SimpleDateFormatter模式,以便返回秒旁边的小数部分。
我使用了yyyy-MM-dd hh:mm:ss ,但只返回到秒,并忽略了秒(.969774)旁边的分数。 我还需要帮助返回这个小数部分,精度为6位数。
格式化java.util.Date
(或java.sql.Timestamp
)的默认方式只有毫秒精度。 您可以使用yyyy-MM-dd hh:mm:ss.SSS
来获得毫秒精度。
java.sql.Timestamp
实际上具有(最高)纳秒精度(假设数据库服务器和驱动程序实际上支持它)。 在Java 8中格式化它的最简单方法是将时间戳转换为java.time.LocalDateTime
(使用Timestamp.toLocalDateTime()
)并使用java.time
格式化选项,该选项支持最多纳秒。
如果使用Java 7或更早版本,则需要额外的工作,因为普通的日期格式化程序不支持它。 例如,您可以使用带有模式yyyy-MM-dd hh:mm:ss
格式化程序(仅格式化为秒)并自己附加Timestamp.getNanos()
的亚秒秒纳秒(带有适当的零填充)。
您必须有一种获得微秒时间戳的方法。 我将System.currentTimeMillis()与System.nanoTime()结合使用。 然后你需要一种方法来显示它。 您可以将其除以1000并正常显示毫秒,然后显示时间的最后3位数。 即有一个时间就像
long timeUS = System.currentTimeMillis() * 1000 + micros;
这是一个更详细的例子
HiresTimer.java和HiresTimerTest.java
测试打印
2012/04/09T14:22:13.656008 2012/04/09T14:22:13.656840 2012/04/09T14:22:13.656958 2012/04/09T14:22:13.657066 .... 2012/04/09T14:22:13.665249 2012/04/09T14:22:13.665392 2012/04/09T14:22:13.665473 2012/04/09T14:22:13.665581
编辑:相关的代码是
private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss.SSS"); private static final DecimalFormat DF = new DecimalFormat("000"); public static String toString(long timeUS) { return SDF.format(timeUS / 1000) + DF.format(timeUS % 1000); }
在Java 8及更高版本中, java.time包支持解析和操作日期/时间到纳秒精度。 这意味着在几分之一秒内最多9位数。
在Java中处理纳秒并非易事。 除了以单独的方式处理它们之外,我看不到任何优雅的解决方案(使用SimpleDateFormat
格式化日期和时间,使用DecimalFormat
格式化纳秒),例如,如下例所示:
package test; import java.sql.Timestamp; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { Main m = new Main(); m.start(); } private void start() { long time = System.currentTimeMillis(); Date d = new Date(time); Timestamp t = new Timestamp(time); t.setNanos(123456789); System.out.println(d); System.out.println(t); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.'"); NumberFormat nf = new DecimalFormat("000000000"); System.out.println(df.format(t.getTime()) + nf.format(t.getNanos())); } }
package test; import java.sql.Timestamp; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { Main m = new Main(); m.start(); } private void start() { long time = System.currentTimeMillis(); Date d = new Date(time); Timestamp t = new Timestamp(time); t.setNanos(123456789); System.out.println(d); System.out.println(t); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.'"); NumberFormat nf = new DecimalFormat("000000000"); System.out.println(df.format(t.getTime()) + nf.format(t.getNanos())); } }
产生的输出是(在我的国家,我的语言环境):
Mon Apr 09 16:27:27 CEST 2012 2012-04-09 16:27:27.123456789 2012-04-09 16:27:27.123456789