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

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.

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

Related

How to stringify dates with timezones properly in javascript?

In javascript, I have a date in UTC, and I want to stringify it and parse it but maintain it's UTC. I did this code
var f = { f : new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)")}
undefined
JSON.stringify(f)
"{"f":"2019-05-28T00:11:13.000Z"}"
JSON.parse(JSON.stringify(f))
{f: "2019-05-28T00:11:13.000Z"}
You can see that after I stringified it, it changed to the next day. And then when I parse it, it kept it as a string and even of the next day. I want it so that after I parse it, I get back the Date object of Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time).
Does anyone know what's wrong?
Thanks
You can see that after I stringified it, it changed to the next day
No, it didn't. "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" was parsed to a time value of 1559002273000, which defines a moment in time that is that many milliseconds after 1970-01-01T00:00:00Z. It's equivalent to 2019-05-28T00:11:13.000Z (and other timestamps in other time zones). E.g. on a system set to an eastern Australian timezone you'd get "Tue May 28 2019 10:11:13 GMT+1000 (AEST)".
I want it so that after I parse it, I get back the Date object of Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)
The date object has no knowledge of the timezone of the original timestamp, it just stores the time value. The string produced by toString just uses the host system timezone setting to generate a "local" timestamp in the format specified by ECMA-262. Note that the timezone name is implementation dependent and since they aren't standardised, the names and abbreviations differ between implementations. E.g. Safari shows "AEST" and Firefox "Australian Eastern Standard Time".
You can use toLocaleString to generate timestamps for different timezones, but the date object doesn't know what the original timezone was and the format may not be what you want.
Also, toLocaleString uses IANA timezone identifiers (e.g. Africa/Kinshasa), which relate to geographic locations that are used to deduce the applicable timezone rather than common names like "Eastern Daylight Time" which are not standardised and can be ambiguous or obscure. The IANA designators mean things like daylight saving and historic timezone offset changes can be applied more easily than with other designators.

Javascript convert timezone issue

I am facing an issue in converting datetime in current timzone.
I am receiving this date string from server in a format "2015-10-09T08:00:00" which is Central Time but when I convert this date time using new Date(strDate) in GMT+5 its returning me below which is incorrect.
var dateObj = '2015-10-09T08:00:00';
new Date(dateObj); // return me below
Fri Oct 09 2015 13:00:00 GMT+0500 (PKT)
Another way I used is to convert by adding timezone offset and its returning me right result but defiantly failed when daylight saving activated.
dateObj2 = '2015-10-09T08:00:00'+'-06:00';
new Date(dateObj2)// return me below
Fri Oct 09 2015 19:00:00 GMT+0500 (PKT)
I appreciated if anyone help OR suggest me efficient way to handle to timezone conversion with daylight saving in JavaScript?
Thank you.
Note that behavior of the code you wrote differs between the browsers:
new Date('2015-10-09T08:00:00').toString()
// "Fri Oct 09 2015 10:00:00 GMT+0200 (Romance Daylight Time)" // Chrome 46 on Windows 8.1
// "Fri Oct 09 2015 08:00:00 GMT+0200 (Romance Daylight Time)" // Firefox 41 on Windows 8.1
// "Fri Oct 09 2015 08:00:00 GMT+0200 (Romance Daylight Time)" // IE11 on Windows 8.1
// "Fri Oct 9 08:00:00 UTC+0200 2015" // IE10 emulation
// "Fri Oct 9 10:00:00 UTC+0200 2015" // IE9 emulation
// on IE8 it even returns NaN!
(my timezone is Paris)
So, Firefox and IE interpret the provided date as specified as if it were in local timezone of the user, whereas Chrome interprets it as UTC, and when printed, it gets converted to user's timezone.
Checking the MDN docs, this is due to differences in EcmaScript 5 and EcmaScript 6 (2015) specifications. It seems that Chrome follows ES5 spec while Firefox and IE11 follow ES6 spec.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#ECMAScript_5_ISO-8601_format_support (emphasis mine)
The date time string may be in ISO 8601 format. For example,
"2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can
be passed and parsed. The UTC time zone is used to interpret arguments
in ISO 8601 format that do not contain time zone information (note
that ECMAScript 2015 specifies that date time strings without a time
zone are to be treated as local, not UTC).
Unfortunately Date object in JavaScript is famous for its quirks and cross-browser inconsistencies, particularly on ambiguous input.
I wrote here
how you can leverage moment.js or native Intl API to make sure your date will not be converted to user's timezone (the secret is to use UTC manipulating methods).
In general it's best to always specify either both time and UTC offset, or just a UTC timestamp, to make sure your input is unambiguous.
Coming back to your example, you can use following code:
moment('2015-10-09T08:00:00-06:00')
.utcOffset(+300).locale('en_gb').format("LLLL")
// "Friday, 9 October 2015 19:00" cross-browser
in which you say "this is date in UTC-0600, please convert and print it as UTC+0500 (+300 minutes)". Then you can pass in which locale you want it printed (i.e. language + culture specific settings, e.g. en_gb uses 24 hour clock while en_us 12-hour clock) and use multitude of date formats supported by moment.js.

Why is BST (British Summer Time/Daylight Savings Time) being added to my datetime in node?

I'm logging out the following....
dbResponseStub.startTime = new Date(2014,6,13);
console.log(dbResponse[0].startTime);
console.log(new moment(dbResponse[0].startTime).utc().format());
But I am getting...
Fri Jun 13 2014 00:00:00 GMT+0100 (BST)
2014-06-12T23:00:00+00:00
I'm confused because the second one is an hour behind what it should be. Obviously the BST thing that happens in the first one is causing a problem. Anyone know how to turn this off in node so that what time i say it is it will be?
Dates are given in local time.
The first one has BST in it because it is showing you the time zone, and that is the time zone the computer is configured to use.
British Summer Time is an hour ahead of Coordinated Universal Time.
If you want to stay in BST then remove .utc() so you don't convert to it.

Why do different browsers return different results for JavaScript new Date(-105998400000)?

I'm using ASP.NET MVC 3 with the default Json serializer (not Json.NET implemented in MVC4+) and dates from my JsonResults come back looking like /Date(-105998400000)/. I am parsing the number out and newing up a Date with this value, but I get inconsistent results between IE and Chrome.
var date = new Date(-105998400000);
See my jsfiddle in various browsers. My results are:
IE10 - Mon Aug 22 23:00:00 EST 1966
Firefox - Tue Aug 23 1966 00:00:00 GMT-0400 (US Eastern Standard Time)
Chrome - Tue Aug 23 1966 00:00:00 GMT-0400 (US Eastern Daylight Time)
Two of my clients are seeing the August 22 date in Chrome.
Why does a new Date return different values in different browsers with the UTC milliseconds value?
My original implemented answer to this issue is here, using ISO 8601 dates from the Json.NET serializer instead of UTC millisecond offsets from the legacy ASP.NET MVC3 Json serializer.
I did get some insight with this odd outcome thanks to user dandavis.

How is current GMT zone defined in Javascript?

I have just cast a 08/23/2012 to date in javascript:
var value = '08/23/2012';
var newdate = new Date(value);
newdate happens to be Date {Thu Aug 23 2012 00:00:00 GMT+0100 (BST)}
I live in London (GMT 0:00) so where does the +1 assumption come from and how can I set it right?
You're in the Europe/London timezone, with is GMT+0100 during the summer, due to the Daylight Saving Time scheme.
This is why it's usually better to configure systems based on the location, and adapt the timezone by looking up the tz database. Unfortunately, JavaScript implementations in browser are quite poor regarding the general handling of time zones.
London is currently GMT+1 because of Daylight Savings.
If you want dates unaffected by timezones or DST, you need to do two things:
Define dates with a timestamp. A timestamp is a number of milliseconds since the Epoch, and is completely agnostic with regards to timezones and DST
Use the Date.getUTC___() functions to get the date and time in UTC, which is basically GMT but without the daylight savings.

Categories

Resources