I have this code to get the current timestamp so that I can save it as a part of the key in leveldb database.
export default function timestamp() {
var [seconds, nanoseconds] = process.hrtime()
return seconds * 1000000000 + nanoseconds
}
I am wondering are there any downsides to use this function. Or are there any better alternatives to get current timestamp in node.
2 Answers 2
Your code does not work - process.hrtime()
does not return with a timestamp of any useful form unless you compare it to another process.hrtime()
in the same running program (typically used for measuring performance).
From the documentation:
These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals
Bottom line is that the arbitrary time in the past
could be anything, and not the same "epoch" as new Date()
.
There is no way in native JavaScript or Node (without making OS system calls through libraries, etc.) that I know of to get a more granular resolution than the millisecond times from Date.
The shortest one:)
+new Date()
-
\$\begingroup\$ This is what I use (well, I use
timestamp = Date.now()
) but based on OPs code they are looking for nanoseconds. Date.now() only gives you millisecond precision. While that's good enough for me to use as a DB key, for very fast transactions it might not work. \$\endgroup\$billoverton– billoverton2020年01月24日 17:03:42 +00:00Commented Jan 24, 2020 at 17:03