Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
A UNIX timestamp is the number of seconds since January 1, 1970 midnight UTC.
It’s often used so that we can do calculations with time easily.
In this article, we’ll look at how to get the UNIX timestamp from a date object in JavaScript.
The + Operator
We can use the +
operator to convert the date object right to a UNIX timestamp.
For instance, we can write:
+new Date()
The +
operator before the date object triggers the valueOf
method in the Date
object to return the timestamp as a number.
The getTime Method
We can call getTime
to do the same thing.
For instance, we can write:
new Date().getTime()
to return the UNIX timestamp of a date.
Date.now Method
Date.now
is a static method of the Date
constructor that lets us get the current date-times timestamp.
For instance, we can write:
Date.now()
The timestamp is returned in milliseconds, so we have to divide it by 1000 and round it to get the timestamp in seconds.
To do that, we write:
Math.floor(Date.now() / 1000)
Math.floor
rounds the number down to the nearest integer.
We can also round it with Math.round
by writing:
Math.round(new Date().getTime() / 1000);
Number Function
The Number
function is a global function that lets us convert a non-number object or primitive value to a number.
And we can use it to convert a date to a timestamp.
To do that, we write:
Number(new Date())
Then we get the timestamp in seconds returned since it triggers the valueOf
method of the Date
instance like the +
operator.
Lodash _.now Method
Lodash also has a now
method that returns the current timestamp.
To use it, we write:
_.now();
It’ll also return the current date’s timestamp.
Conclusion
There’re many ways to get the timestamp of the current date and time or the date-time that we want with JavaScript.
Top comments (0)