This article will demonstrate the method for getting the Unix timestamp in JavaScript.
How to Get Unix Timestamp in JavaScript?
For getting Unix Timestamp, use the below-given JavaScript methods:
Let’s discuss these methods one by one!
Method 1: Get Unix Timestamp Using getTime() Method
There are numerous functions available for working with dates and times in the JavaScript Date object. One of them is the “getTime()” method. It provides the milliseconds since January 1, 1970 (Unix Epoch). The getTime() method always represents time using the UTC format.
Syntax
Follow the below-provided syntax for getting Unix timestamp with the help of getTime() method:
The above-mentioned method does not take any argument.
Let’s check out an example for getting Unix Timestamp using the getTime() method.
Example
Firstly, we will create a variable “tDate” that stores the date as a string:
Then, create an instance of the Date object by passing the date string stored in “tDate”:
Call the getTime() method and divide it by “1000” to get the time in seconds because the Unix timestamp represents the number of seconds between a particular date and the Unix Epoch while the JavaScript getTime() method gives result in milliseconds:
Finally, print the timestamp using the “console.log()” method:
Output
Let’s move on to the next method!
Method 2: Get Unix Timestamp Using Date.now() Method
The “now()” method of the Date Object also helps to get the Unix timestamp. It offers the most recent millisecond UTC timestamp. It is the static method; that’s why it must be called with Date Object. It almost supports all browsers except IE8 and previous versions.
Syntax
Use the given syntax for now() method of the Date Object:
The “Date.now()” method takes no argument and gives the current time in milliseconds.
Example
Now, we will invoke the “Date.now()” method by dividing it by 1000 to get the Unix timestamp in seconds:
It can be seen that the Unix timestamp is displayed in seconds:
We have provided the simplest methods for getting the Unix timestamp in JavaScript.
Conclusion
For getting a Unix timestamp, you can use the JavaScript predefined methods of the Date Object, including the getTime() method or Date.now() method. It is preferable to use Date.now() rather than getTime() because it does not create a new instance of the Date object. This article demonstrates the methods for getting Unix Timestamp in JavaScript.