How to stringify dates with timezones properly in javascript? - 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.

Related

String to date converter issue in js

My local machine in EST timezone.
I'm trying to convert date string to date object in js but getting an day before from date string in date object.
new Date('2020-04-03') for this i'm getting Thu Apr 02 2020 20:00:00 GMT-0400 (Eastern Daylight Time) this output.
new Date('2020/04/03') for this i'm getting Fri Apr 03 2020 00:00:00 GMT-0400 (Eastern Daylight Time) this output.
console.log(new Date('2020-04-03'))
console.log(new Date('2020/04/03'))
I don't know what is the difference between these can anyone explain that?
How i fix this issue?
The reason why the two date parsings give you different results is because it's triggering two different date handling modes.
In one case, 2020-04-03, it's treating the date as an simplified version of ISO 8601 format, for which JavaScript creates a date in the UTC time zone if no time zone is specified.
The second date, 2020/04/03, is not in an officially supported format, so JavaScript falls back to an implementation-specific parsing of the date, so it may not even be consistent across browsers. In that case, it's choosing to use your local time zone.
The MDN article on Date.parse() offers a detailed explanation of how date parsing works in the JavaScript standard and how non-standard behaviors exist among browsers in some cases.
In short, it's a good idea to stick with ISO 8601 dates whenever possible, not only because JavaScript handles them in a consistent way, but they're also easily sorted, and they're widely supported across many programming systems.
Try new Date('2020-04-03 00:00:00')
By default, the date string is parsed in UTC timezone. When you output a date, by default it converts it to your local timezone set by your browser.
To solve, you can enter your date as the UTC equivalent, or simply do as the others have stated here and include the timezone in your date string
let date = new Date('2020-04-03 EST');

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.

JavaScript Date instances confusion

Let's say I create a new Date(), log it to the console, and see:
Date.toString() = Sun Sep 27 2015 00:00:00 GMT+0100 (GMT Daylight Time)
This tells me that the date is Sept. 27th, 2015, and my timezone is an hour ahead of UTC.
Now let's say I serialize this Date by calling toISOString() on it. The result of toISOString() is:
2015-09-26T23:00:00.000Z
Now let's say I send this toISOString() value off to a server.
Am I correct in asserting that the server receiving only the 2015-09-26T23:00:00.000Z cannot know that the original Date on the client browser was the 27th, not the 26th?
(In other words, the timezone offset would also need to be sent to the server to know the Date was for the 27th.)
yes, you are correct in that, but you could guess the timezone based on the ip address.

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.

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.
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

Categories

Resources