如何生成时间戳unix epoch格式的nodejs?

问题描述 投票:40回答:3

我正在尝试使用端口2003将数据发送到石墨碳缓存进程

1)Ubuntu终端

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

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

Graphite以此格式度量标准路径值时间戳\ n了解度量标准

javascript node.js graphite
3个回答
108
投票

本机JavaScript Date系统在几秒内工作,而不是秒,但除此之外,它与UNIX中的“纪元时间”相同。

你可以通过执行以下操作来舍入一小段时间并获得UNIX纪元:

Math.floor(new Date() / 1000)

17
投票

如果可以,我强烈建议使用moment.js。要获得自UNIX纪元以来的毫秒数,请执行此操作

moment().valueOf()

要获得自UNIX纪元以来的秒数,请执行此操作

moment().unix()

你也可以像这样转换时间:

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

我一直这样做。

要在Node上安装moment.js

npm install moment

并使用它

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

ref


0
投票

Helper方法简化了它,将以下内容复制/粘贴到JS上:

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

现在,您可以通过简单的调用在任何地方使用它:

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

演示:

     
    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())
© www.soinside.com 2019 - 2024. All rights reserved.