This post will discuss how to get the current timestamp in JavaScript. The solution should return the total number of milliseconds that elapsed between Unix Epoch and the current date.

Unix Epoch time is a way of representing a timestamp by representing the time as the number of seconds since 1 January 1970 00:00:00 UTC. To get the current timestamp in JavaScript, you can use one of the following functions:

1. Using Date.now() function

The recommended function is to use the static Date.now() function, which is a built-in function that returns the number of milliseconds since the Unix Epoch. Since now() is a static function, it doesn’t create a new instance of the Date object. This is demonstrated below:

Download  Run Code

2. Using valueOf() or getTime() function

Another approach is to call the valueOf() or getTime() function, which returns the same value as Date.now(), but using an instance of the Date object. This function returns the primitive value of a Date object, which is the same as the UNIX timestamp.

Download  Run Code

 
If you use jQuery in your application, you can use the $.now() function, which is just a shorthand for the number returned by the expression (new Date).getTime().

Download Code

3. Using Number() constructor or Unary plus operator

A third way to get the current timestamp in JavaScript is using the Number() constructor, which is a built-in function that creates a number object from a given value. You can use it to convert a Date object to a number that represents the number of milliseconds since Unix Epoch.

Download  Run Code

 
Alternatively, you can use the expression +new Date(), which uses the unary plus operator (+) to converts a Date object into a Number. This is equivalent to calling Number(date), but shorter and less readable.

Download  Run Code

4. Using Moment.js Library

The Moment.js library is a popular library that simplifies working with dates and times in JavaScript. The moment() function returns a moment object that wraps a Date object and provides many useful functions and properties. You can use the valueOf() or unix() function to get the timestamp in milliseconds or seconds, respectively, from the moment object.

Download Code

That’s all about getting the current timestamp in JavaScript.