Get the Epoch Time in JavaScript

It is very simple to get an epoch time in Javascript. Javascript’s date object has a method named valueOf, which returns the number of microseconds since January 1, 1970 UTC. This isn’t exactly what we want though, because we intend to have a value in seconds and not microseconds. Fortunately, we can just divide by 1000, then remove the floating point by rounding.

I’m not convinced that I would personally need to get the epoch time in Javascript, since I normally only use epoch times on the server, but perhaps I will run into a situation one day where I need to store more than one epoch time and then submit them to the server. Whatever the case may be, this is how to get the current epoch time:

var d = new Date();
var epoch = Math.round( d.valueOf() / 1000 );