How to compute the timestamp in JavaScript

Many sources use the term timestamp to refer specifically to Unix time, the number of seconds since 00:00:00 UTC on January 1, 1970. In JavaScript you can use the built-in object Date to compute this timestamp. Here follows an example:

 
var ts = Date.UTC('2007', '09', '28') / 1000;
alert(ts);

The previous code displays an alert with the number of seconds between 00:00:00 UTC on January 1, 1970 and 00:00:00 UTC on October 28, 2007.

How it works:

UTC is a static method of the Date object. The complete signature of this method is the following:

UTC(year, month, [day], [hours], [minutes], [seconds], [milliseconds])

Note that the parameters between square brackets are optional. The UTC method returns the number of milliseconds using UTC (Universal Time Coordinated). Hence the following code:

 
Date.UTC('2007', '09', '28') / 1000;

computes the number of seconds between 00:00:00 UTC on January 1, 1970 and 00:00:00 UTC on October 28, 2007. Note that the month parameter ranges from 0 (Jan) to 11 (Dec).

comments powered by Disqus