[javascript] Get a UTC timestamp

How can I get the current UTC timestamp in JavaScript? I want to do this so I can send timestamps from the client-side that are independent of their timezone.

This question is related to javascript time

The answer is


As wizzard pointed out, the correct method is,

new Date().getTime();

or under Javascript 1.5, just

Date.now();

From the documentation,

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

If you wanted to make a time stamp without milliseconds you can use,

Math.floor(Date.now() / 1000);

I wanted to make this an answer so the correct method is more visible.

You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s on a Unix terminal.


new Date().getTime();

For more information, see @James McMahon's answer.


You can use Date.UTC method to get the time stamp at the UTC timezone.

Usage:

var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , 
      now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());

Live demo here http://jsfiddle.net/naryad/uU7FH/1/


"... that are independent of their timezone"

var timezone =  d.getTimezoneOffset() // difference in minutes from GMT