简体   繁体   中英

UTC timestamp in javascript

I have countdown plugin which takes a timestamp and returns a countdown in form of days / houers / minutes .... all my timestamps are stored in UTC timezone .

So this used to work fine until i've changed my website timezone .

I have to change my timezone from time to time ... so now all the countdowns that i get are wrong .

This is how my plugin works basically

time_left_ms = given timestamp - currentstime stamp / 1000 ;

eg

var time_left = Math.floor((options.timestamp - (new Date())) / 1000);

So i thought i can fix it using UTC timestamp like this

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

left = Math.floor((options.timestamp - (utc)) / 1000);

but still the same wrong result ... after that i've tried this to see whats going on

console.log( d +'####'+utc +'####'+d.getTime());

and this is the output

Thu Sep 19 2013 19:10:13 GMT+0330 (Iran Standard Time)##1379605213010##1379605213010

whats wrong ? apparently time zone is on Asia/Thran ... but why do i get the same timestamp for Asia/tehran and UTC ? ... both are 1379605213010

Dates are specified as the number of milliseconds since Jan 1, 1970 UTC:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. (...)

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC.

Date.prototype.getTime returns this internal time value .

This return UTC

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

and This returns UTC

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime

It must be the same

I don't think there is a numeric representation of time for a time zone, it's always UTC

var x = new Date();
x.getTime();   //1379646809459
x.valueOf();   //1379646809459

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM