How to generate timestamp unix epoch format nodejs

2020-05-18 04:16发布

问题:

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

1) Ubuntu terminal

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

2) NODEJS

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

回答1:

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)


回答2:

If you can, I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do

moment().valueOf()

To get the number of seconds since UNIX epoch, do

moment().unix()

You can also convert times like so:

moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()

I do that all the time.

To install moment.js on Node,

npm install moment

and to use it

var moment = require('moment');
moment().valueOf();

ref



回答3:

Helper methods that simplifies it, copy/paste the following on top of your JS:

Date.prototype.toUnixTime = function() { return this.getTime()/1000|0 };
Date.time = function() { return new Date().toUnixTime(); }

Now you can use it wherever you want by simple calls:

// Get the current unix time: 
console.log(Date.time())

// Parse a date and get it as Unix time
console.log(new Date('Mon, 25 Dec 2010 13:30:00 GMT').toUnixTime())

Demo:

     
    Date.prototype.toUnixTime = function() { return this.getTime()/1000|0 };
    Date.time = function() { return new Date().toUnixTime(); }

    // Get the current unix time: 
    console.log("Current Time: " + Date.time())

    // Parse a date and get it as Unix time
    console.log("Custom Time (Mon, 25 Dec 2010 13:30:00 GMT): " + new Date('Mon, 25 Dec 2010 13:30:00 GMT').toUnixTime())



回答4:

In typescript, simply run Math.floor(new Date().getTime() / 1000)

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

I'm currently running Node 13.7.0



回答5:

the AWS sdk includes utility functions for converting the amazon date format.

For example, in a call back from an S3 get object, there is a property 'LastModified' that is in the amazon date format. (it appears they are doing nothing but exporting the standard Date class for their date properties such as S3 object 'LastModified' property) That format includes some utilities for various formats built in (unfortunately, none for unix epoch):

let awsTime = response.LastModified
console.log("Time Formats",{
    "String"           : awsTime.toString(),
    "JSON"             : awsTime.toJSON(),
    "UTCString"        : awsTime.toUTCString(),
    "TimeString"       : awsTime.toTimeString(),
    "DateString"       : awsTime.toDateString(),
    "ISOString"        : awsTime.toISOString(),
    "LocaleTimeString" : awsTime.toLocaleTimeString(),
    "LocaleDateString" : awsTime.toLocaleDateString(),
    "LocaleString"     : awsTime.toLocaleString()
})
/*
Time Formats {
  String: 'Fri Sep 27 2019 16:54:31 GMT-0400 (EDT)',
  JSON: '2019-09-27T20:54:31.000Z',
  UTCString: 'Fri, 27 Sep 2019 20:54:31 GMT',
  TimeString: '16:54:31 GMT-0400 (EDT)',
  DateString: 'Fri Sep 27 2019',
  ISOString: '2019-09-27T20:54:31.000Z',
  LocaleTimeString: '16:54:31',
  LocaleDateString: '2019-9-27',
  LocaleString: '2019-9-27 16:54:31'
}
*/

However, the AWS utils function includes a 'date' module with other functions including a unixTimestamp method:

let awsTime = response.LastModified
let unixEpoch = Math.floor(AWS.util.date.unixTimestamp(awsTime))

Note: this method returns a float value by default. Thus the Math.floor()

Function code from aws-sdk.js (latest):

/**
 * @return [Integer] the UNIX timestamp value for the current time
 */
 unixTimestamp: function unixTimestamp(date) {
     if (date === undefined) { date = util.date.getDate(); }
     return date.getTime() / 1000;
 }

There are also methods for rfc822 and iso8601