Js-如何生成时间戳 unix epoch 格式?

我试图发送数据到石墨碳缓存进程的端口2003使用

Ubuntu 终端:

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();
});

当我在 ubuntu 上使用终端窗口命令发送数据时,它工作得很好。但是,我不知道如何从 nodejs 发送时间戳 unix 新纪元格式?

Grpahite 理解这种格式的度量指标——指标 _ 路径值时间戳

谢谢!

131279 次浏览

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.

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

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())

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

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

Post ECMAScript5 you can use:

Math.floor(Date.now() / 1000);

which generates epoch timestamp in seconds.

Using momentjs:

The following two variables have the same value:-

console.log(moment().format('X'))
console.log(moment.utc().format('X'))

Using Date() built-in:

console.log(new Date().getTime())   // including fractional seconds
console.log(Math.floor(new Date().getTime()/1000))    // up to seconds