Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert unix timestamp to JavaScript date object (consider time zone)

var date = new Date(1257397200000​);
document.write(date);
​

Ran the code above I got Wed Nov 04 2009 23:00:00 GMT-0600 (Central Standard Time)

I am looking for a way to create date object based on different time zone, say for that time stamp I want to obtain date object like Thursday, November 5th 2009, 00:00:00 (GMT -5).

Note that the dates are different according to above two time zones, though they represent same point in time. I am in CST, is that why the created object is generated using CST?

Thank you.

like image 556
sozhen Avatar asked Jul 25 '12 18:07

sozhen


People also ask

What timezone is JavaScript date object?

JavaScript's Date object tracks time in UTC internally, but typically accepts input and produces output in the local time of the computer it's running on.

Does timestamp include timezone?

Show activity on this post. The date timestamp also doesn't include timezone information, yet a lot of people use it. Of course, that of itself is not an answer. It's valid to use timestamp and date for any timestamps and dates which are always in the same timezone, or are being stored relative to some known timezone.

How do I convert one time zone to another in JavaScript?

To convert a date to another time zone: Use the toLocaleString() method to get a string that represents the date according to the provided time zone. Pass the result to the Date() constructor. The returned Date object will have its date and time set according to the provided time zone.

How does JavaScript handle different time zones?

The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.


1 Answers

No, these dates aren't different as they don't represent different point in time. The both represent Thu, 05 Nov 2009 05:00:00 GMT.

Date object in JavaScript is time-zone independent, it only represents point in time. The fact that Date.toString() includes time zone is very misleading, there is no time-zone information in Date. It is only a wrapper around milliseconds since epoch.

The time zone you see is based on OS/browser locale. You cannot create Date object in different time-zone. Consider using getUTC*() family of methods to get browser time-zone agnostic values.

BTW your example code prints:

Thu Nov 05 2009 06:00:00 GMT+0100 (CET)

on my computer - and this is still the same point in time.

See also

  • Annoying javascript timezone adjustment issue
like image 96
Tomasz Nurkiewicz Avatar answered Oct 16 '22 03:10

Tomasz Nurkiewicz