3
\$\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.

asked Jan 1, 2020 at 14:48
\$\endgroup\$

2 Answers 2

3
\$\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.

answered Jan 7, 2020 at 22:33
\$\endgroup\$
0
0
\$\begingroup\$

The shortest one:)

+new Date() 
answered Jan 7, 2020 at 20:16
\$\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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.