Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate timestamp unix epoch format nodejs?

I am trying to send data to graphite carbon-cache process on port 2003 using

Ubuntu terminal:

echo "test.average 4 `date +%s`" | nc -q0 127.0.0.1 2003 

Node.js:

var socket = net.createConnection(2003, "127.0.0.1", function() {     socket.write("test.average "+assigned_tot+"\n");     socket.end(); }); 

It works fine when i send data using the terminal window command on my ubuntu. However, i am not sure how to send timestamp unix epoch format from nodejs ?

Grpahite understands metric in this format metric_path value timestamp\n

like image 615
user3846091 Avatar asked Aug 11 '14 19:08

user3846091


People also ask

How do I convert timestamp to epoch?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

How is epoch timestamp calculated?

Epoch Time Difference FormulaMultiply the two dates' absolute difference by 86400 to get the Epoch Time in seconds – using the example dates above, is 319080600.

Is epoch time always 10 digits?

No. epoch time is how time is kept track of internally in UNIX. It's seconds, counting upward from January 1st, 1970.


1 Answers

The native JavaScript Date system works in milliseconds as opposed to seconds, but otherwise, it is the same "epoch time" as in UNIX.

You can round down the fractions of a second and get the UNIX epoch by doing:

Math.floor(+new Date() / 1000) 

Update: As Guillermo points out, an alternate syntax may be more readable:

Math.floor(new Date().getTime() / 1000) 

The + in the first example is a JavaScript quirk that forces evaluation as a number, which has the same effect of converting to milliseconds. The second version does this explicitly.

like image 110
tadman Avatar answered Sep 19 '22 10:09

tadman