101

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

Thanks!

4
  • +new Date() == the unix date
    – dandavis
    Aug 11, 2014 at 19:04
  • @dandavis Actually that's just the date. You need to call getTime() to get milliseconds.
    – tadman
    Aug 11, 2014 at 19:08
  • @tadman: no, the "+" coerces the date into it's valueOf() value, which is a number representing the # of ms since 1970 started. in short, you never need getTime()
    – dandavis
    Aug 11, 2014 at 19:10
  • That's an interesting optimization. That value is still milliseconds, so you'll need to divide by 1000 to get seconds.
    – tadman
    Aug 11, 2014 at 19:13

8 Answers 8

197

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.

7
  • 1
    same as ~~ (new Date/1000) or Math.floor(new Date/1000)
    – dandavis
    Aug 11, 2014 at 19:11
  • @dandavis Edited accordingly. Thanks for the note there. I've used floor here to be sure it's an integer value because traditional time_t times do not have decimals.
    – tadman
    Aug 11, 2014 at 19:14
  • 3
    Typescript will complain about this one since the date is another type than number also to Date.parse(new Date()) / 1000 etc, consider : Math.floor(new Date().getTime() / 1000) OR Math.floor(+new Date() / 1000)
    – edelwater
    Sep 1, 2020 at 17:04
  • 1
    I vote up this answer because it is useful, but I have to said I prefer the more easy to read new Date().getTime() over the +newDate() Oct 12, 2020 at 23:17
  • 1
    Even shorter: Math.floor(Date.now() / 1000)
    – jakub.g
    Oct 27, 2021 at 9:56
25

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

2
  • 11
    Are there any particular advantages to using moment.js over something like Math.floor(new Date() / 1000)?
    – Alex
    Oct 29, 2015 at 1:11
  • 1
    @Alex - For me, I prefer moment.js's concise syntax and more comprehensive functionality. You can do things like moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').add(3, 'days')
    – FullStack
    Oct 30, 2015 at 2:41
6

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

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

1
5

Post ECMAScript5 you can use:

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

which generates epoch timestamp in seconds.

0
2

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
1

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

0

Another way to generate a ISO date-time stamp in bash, to match a format generated by nodejs:

date --utc --iso-8601=ns | sed -E 's|^(.*),([0-9]{3}).*$|\1.\2Z|gi'

The output is:

2024-01-12T02:25:25.864Z

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.