如何生成时间戳记unix epoch格式的nodejs? [英] How to generate timestamp unix epoch format nodejs?

查看:204
本文介绍了如何生成时间戳记unix epoch格式的nodejs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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纪元格式?

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以这种格式理解指标metric_path值时间戳记\ n

Grpahite understands metric in this format metric_path value timestamp\n

推荐答案

原生JavaScript Date系统以毫秒为单位工作,而不是秒,但是在其他情况下,它是相同的纪元时间".就像在UNIX中一样.

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

您可以舍入一秒的时间,并通过以下操作获得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)

第一个示例中的+是一个JavaScript怪癖,它强制将求值运算为数字,具有转换为毫秒的相同效果.第二个版本明确地做到了这一点.

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.

这篇关于如何生成时间戳记unix epoch格式的nodejs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆