如何为秒值打印高达 6 位精度的时间 [英] How to print time up to 6 digits of precision for seconds value

查看:13
本文介绍了如何为秒值打印高达 6 位精度的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列中有一个时间戳类型的值.假设我有一个值 2007-05-04 08:48:40.969774

I have a value in column which is of type timestamp. Lets say I have a value 2007-05-04 08:48:40.969774

现在,当尝试从数据库中获取值并将此时间戳值返回给函数时,我应该使用什么 SimpleDateFormatter 模式,以便也返回秒旁边的小数部分.

Now, when trying to fetch the value from the database and return this timestamp value to a function, what SimpleDateFormatter pattern should I use so that the fraction part beside the seconds also gets returned.

我使用了 yyyy-MM-dd hh:mm:ss,但它只返回到秒数,并忽略秒数旁边的分数 (.969774).我还需要帮助以 6 位精度返回这个小数部分.

I have used yyyy-MM-dd hh:mm:ss, but that only returns till the seconds and ignores the fraction present beside the seconds(.969774). I need help in returning this fraction part also, with a 6-digits precision.

推荐答案

java.util.Date(或java.sql.Timestamp)的默认格式化方式只有毫秒精度.您可以使用 yyyy-MM-dd hh:mm:ss.SSS 来获得毫秒精度.

The default ways of formatting a java.util.Date (or java.sql.Timestamp) has only millisecond precision. You can use yyyy-MM-dd hh:mm:ss.SSS to get that millisecond precision.

java.sql.Timestamp 实际上确实具有(高达)纳秒精度(假设数据库服务器和驱动程序实际上支持它).在 Java 8 中格式化它的最简单方法是将时间戳转换为 java.time.LocalDateTime(使用 Timestamp.toLocalDateTime())并使用 javajava.time.format.DateTimeFormatter 中的 .time 格式选项,最多支持纳秒.

A java.sql.Timestamp actually does have (up to) nanosecond precision (assuming the database server and the driver actually support it). The easiest way to format it in Java 8 is to convert the timestamp to a java.time.LocalDateTime (using Timestamp.toLocalDateTime()) and use the java.time formatting options in java.time.format.DateTimeFormatter which support up to nanoseconds.

如果您使用 Java 7 或更早版本,则需要付出一些额外的努力,因为普通的日期格式化程序不支持它.例如,您可以使用带有模式 yyyy-MM-dd hh:mm:ss 的日期格式化程序(仅格式化为秒)并附加亚秒纳秒(带有适当的零填充)Timestamp.getNanos() 你自己.

If you use Java 7 or earlier it will take some extra effort, as the normal date formatters don't support it. For example you could use a dateformatter with pattern yyyy-MM-dd hh:mm:ss (to only format up to seconds) and append the sub-second nano seconds (with appropriate zero-padding) of Timestamp.getNanos() yourself.

这篇关于如何为秒值打印高达 6 位精度的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆