Date.now () Method¶
This method can be supported in almost all browsers. The Date.now () method is aimed at returning the number of the milliseconds, elapsed since the Unix Epoch. As now() is considered a static method, it is not capable of creating a new instance of the Date object. The example below demonstrates it:
let ms = Date.now(); console.log(ms);
valueOf () Method¶
An alternative option is the value0f method that returns the primitive value of a Date object that has the same quantity of milliseconds since the Unix Epoch.
Here is an example:
let milliseconds = new Date().valueOf(); console.log(milliseconds);
You have the option of implementing the getTime () method for getting UNIX timestamp that is equivalent to the value0f() method.
The example will look like this:
let milliseconds = new Date().getTime(); console.log(milliseconds);
Another approach is to use the unary plus operator that converts the Date object into milliseconds. You can implement it by calling the value0f() method of the Date object, like here:
let milliseconds = +new Date(); console.log(milliseconds);
For getting a time value as a number data time, you may act like this:
let milliseconds = Number(new Date()); console.log(milliseconds);
If you already use the Moment.js library, you can also use the value0f() method, outputting the milliseconds’ quantity after the Unix Epoch. It is demonstrated in the following example:
let moment = require('moment'); let milliseconds = moment().valueOf(); console.log(milliseconds)
As an alternative method, you can use the unix () in case you need to get the number of seconds since UNIX epoch.