Get a UTC timestamp [duplicate]

Get a UTC timestamp [duplicate]

This question already has an answer here:

How do I get a UTC Timestamp in JavaScript?

15 answers

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.

Solutions/Answers:

Solution 1:

new Date().getTime();

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

Solution 2:

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.

Solution 3:

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

Related:  How to make a page redirect using JavaScript? [duplicate]

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/

Solution 4:

“… that are independent of their timezone”

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

Solution 5:

The best way to do that is:

Math.round(new Date()/1000)

This will return UNIX timestamp!