How to Get a Timestamp in JavaScript

In this snippet, we are going to explore the ways of getting a timestamp in JavaScript in a fast and comfortable way.

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

getTime() Method

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

Unary plus

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

Number Constructor

For getting a time value as a number data time, you may act like this:

let milliseconds = Number(new Date());
console.log(milliseconds);

Moment.js

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.

Date and Time in JavaScript

As date and time are a regular part of our lives, they are also considered prominent in programming. In JavaScript, you can create a website with a calendar, an interface for setting up appointments, and so on. All these are possible due to the built-in Date object. It stores date and time and provides a range of built-in for formatting and managing data.

So, the Date object in Javascript is used for representing both date and time. You can subtract the dates in JavaScript, giving their difference in milliseconds because the Date is transformed into timestamp when converted to a number.

Do you find this helpful?

Related articles