問題描述
我在列中有一個(gè)時(shí)間戳類型的值.假設(shè)我有一個(gè)值 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
現(xiàn)在,當(dāng)嘗試從數(shù)據(jù)庫中獲取值并將此時(shí)間戳值返回給函數(shù)時(shí),我應(yīng)該使用什么 SimpleDateFormatter 模式,以便也返回秒旁邊的小數(shù)部分.
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,但它只返回到秒數(shù),并忽略秒數(shù)旁邊的分?jǐn)?shù) (.969774).我還需要幫助以 6 位精度返回這個(gè)小數(shù)部分.
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
)的默認(rèn)格式化方式只有毫秒精度.您可以使用 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
實(shí)際上確實(shí)具有(高達(dá))納秒精度(假設(shè)數(shù)據(jù)庫服務(wù)器和驅(qū)動程序?qū)嶋H上支持它).在 Java 8 中格式化它的最簡單方法是將時(shí)間戳轉(zhuǎn)換為 java.time.LocalDateTime
(使用 Timestamp.toLocalDateTime()
)并使用 java
格式選項(xiàng),最多支持納秒.java.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 或更早版本,則需要付出一些額外的努力,因?yàn)槠胀ǖ娜掌诟袷交绦虿恢С炙?例如,您可以使用帶有模式 yyyy-MM-dd hh:mm:ss
的日期格式化程序(僅格式化為秒)并附加亞秒納秒(帶有適當(dāng)?shù)牧闾畛?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.
這篇關(guān)于如何為秒值打印高達(dá) 6 位精度的時(shí)間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!