Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating JavaScript date time with offset

I am experiencing some unexpected results with a GMT time zone offset calcultaion.

I am using the ExtJS date class to help calculate the time that a message arrives from the server at GMT 0 to the user's local machine which is currently GMT +8.

I thought that if i calculated the offset, then added that to the timestamp in seconds then i could use the following calculation to give me a string to format as i please.

var d = new Date((stamp + offset) * 1000);

stamp is the date/time in seconds as is the offset.

This returns the current date and time at my location but plus 8 hours. If i do not add the offset then the time is correct.

Does the method new Date() automatically give me the date/time at local time?

like image 793
RyanP13 Avatar asked Jan 03 '13 07:01

RyanP13


3 Answers

just insert a unix timestamp containing the thousandth of a second. that unix timestamp should be UTC 0 and javascript will look up the local timezone of the clients computer and will calculate it.

as you can see behind this link, there are some UTC methods wich give you the time without local time offset. maybe this might be what you search for (in case you really want to set the timezone yourself).

edit:

new Date().getTimezoneOffset() will show you the difference between the local timezone and utc but you should consider using the utc methods.

like image 111
GottZ Avatar answered Nov 10 '22 12:11

GottZ


Just adding this in case it helps others looking latter. May be wrong but works for what I needed.

I have the user's offset stored in seconds.

offset assumed in seconds change the (offset * 1000) to make sure offset gets converted to milliseconds if your offset not in seconds.

function offsetDate(offset){
            var d = new Date(new Date().getTime() + (offset * 1000));
            var hrs = d.getUTCHours();
            var mins = d.getUTCMinutes();
            var secs = d.getUTCSeconds();
            //simple output
            document.write(hrs + ":" + mins + ":" + secs);
like image 35
Tribe Avatar answered Nov 10 '22 13:11

Tribe


From the looks of it, stamp is your local time including timezone offset. JavaScript has no knowledge of the timezone of the server, it's (mainly) a client-side language.

like image 1
Cerbrus Avatar answered Nov 10 '22 11:11

Cerbrus