2
\$\begingroup\$

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.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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.

\$\endgroup\$
0
0
\$\begingroup\$

The shortest one:)

+new Date() 
\$\endgroup\$
1
  • \$\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\$ Commented Jan 24, 2020 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.