javascript behaves differently in different browsers - javascript

I am working on a project which need to deal with a lot of "dates". I notice that sometimes javascript behaves differently in different browsers:
code:
new Date("Mar 30, 2017".replace(',', '').replace(/ /g, '/'))
I know I don't need to use replace to create date, but this code gives me interesting different result from Chrome and Safari.
While I run:
"Mar 30, 2017".replace(',', '').replace(/ /g, '/')
Both Chrome and Safari will gives me: "Mar/30/2017". But when I try to turn the result into a Date object, the interesting result will be:
Chrome: Thu Mar 30 2017 00:00:00 GMT-0700 (PDT)
Firefox: Date 2017-03-30T07:00:00.000Z
Safari: Invalid Date
I have already checked Javascript version of both browsers, and they are using the same version (1.7). Can anyone explain why Chrome behaves differently than Safari in this regard?
UPDATE
I know "Mar/30/2017" is not a valid Date format. But my question is why javascript behaves differently in different browsers. For those answers complaining about my Date format. Please read the question before answer it. I will take #Felix Kling 's answer, and thanks for all answers all the same.

Can anyone explain why Chrome behaves differently than Safari in this regard?
The specification says that handling unknown date formats is implementation dependent:
[...] The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. [...]
Safari and Chrome use different JavaScript engines and therefore their behavior can (and do) differ in this case.

Related

JS offset of a date on specific browser/configuration

I've an API that returns birthdate as 2020-11-24T00:00:00 to a React app. That react app uses that portion to display it:
new Date("2020-11-24T00:00:00").toLocaleDateString();
The issue is that on my browser and all browsers I have seems to give no issue: date is correclty shown. One or two customer complains about ir because they see the date 23/11/2020 (one dat before). I cannot reproduce the bug.
As I understood, Dates can be interpreted by browser as Zulu date so browser can translate the date from GMT+0 to browser's region. Right. Now I have to try to reproduce the bug in order to fix it and And I simply cannot because of misunderstanding.
First postulate: Date("2020-11-24T00:00:00") is going wrong, let's try that: fiddle => no, I cannot reproduce with my browser
Second postulate: .toLocaleDateString() is going wrong, let's try that: [fiddle][2] => no, I cannot reproduce with my browser when changing Location in Chrome.
How can I reproduce the issue in order to fix it?
The current ECMAScript standard obliges your example date string to be interpreted as a local date/time, because the time part is included and the timezone part is not.
Through time the rules for parsing strings have become a bit more standardized, but older JavaScript engines may behave differently. See for instance a post from 2013 or 2017 where a difference was reported (at that time). It is likely that some of your users run that JavaScript on much older engines which interpret this type of date string as UTC (as if suffixed by "Z").
Mozilla Contributors write about using Date.parse (which uses the same parser as when the string is passed to the constructor):
Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
To remove all ambiguity also for older browsers, parse the string yourself:
var dateStr = "2020-11-24T00:00:00";
var dateArr = dateStr.match(/\d+/g);
var date = new Date(dateArr[0], dateArr[1]-1, dateArr[2]); // Add time parts if needed
// Guaranteed to be reporting on the 24th of November 2020 (in locale format)
console.log(date.toLocaleDateString());

Date differences between Chrome & Firefox

I am getting an odd difference between Firefox and Chrome using the same bit of code:
var d = new Date('2019', '4', '4');
In Chrome I get the expected result: May 04 2019
In Firefox I get the following result: 2019-05-03
Why is Firefox 1 day out?
Here are some screenshots from the consoles in both browsers:
Chrome:
Firefox:
Those are the same date/time. The difference is that the first one is being shown to you in BST (British Summer Time, GMT+0100), and the second one is being shown to you in GMT (the Z on the end tells you that).
The Date constructor constructs dates in local time, which for you apparently is currently BST (for me, too :-) ). Since you haven't specified a time, it defaults to midnight. Firefox just shows you that in GMT, which is an hour earlier than midnight BST, hence the previous day.
Side note: The arguments you provide to new Date should be numbers, not strings. Although the date constructor will coerce for you, it's best practice not to rely on it.

getTime() not working on Safari the way it works on Chrome

What's the best way to get this to work on both Chrome and Safari? Works fine on Chrome. Returns NaN on Safari.
new Date("2018-11-22 14:24:34 -0800").getTime()
You shouldn't pass the date as a String to the constructor of Date because that causes Date.parse() to be called.
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
To mitigate those differences in implementation, I recommend you use a library like moment.js.
Try using this for the safari browser support:
new Date(("2018-11-22 14:24:34").replace(/-/g, "/")).getTime().valueOf()

Javascript Date.parse bug when dash-delimited and starts with year

Am seeking confirmation if this is a bona fide documentation and/or implementation bug with Javascript's Date.parse method.
The docs I'm referring to are at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse and they say 'If you do not specify a time zone, the local time zone is assumed.'
But the following code shows that, despite not specifying a time zone, local time is not being assumed (but rather my timezone offset is being applied), if the string passed to Date.parse begins with the 4-digit year representation, and is dash-delimited.
var euroStyleDate = '2011-10-04';
var amerStyleDate = '10/04/2011';
var euroStyleParsed = Date.parse(euroStyleDate);
var amerStyleParsed = Date.parse(amerStyleDate);
console.log(euroStyleParsed); //1317686400000
console.log(amerStyleParsed); //1317700800000
console.log(new Date(euroStyleParsed));
//Date {Mon Oct 03 2011 20:00:00 GMT-0400 (Eastern Daylight Time)}
console.log(new Date(amerStyleParsed));
//Date {Tue Oct 04 2011 00:00:00 GMT-0400 (Eastern Daylight Time)}
There may even be other cases, and I'm sure I'm not the first to discover this if I am incorrect. So beyond confirmation, I'd surely love to be pointed at more in-depth information on this if anybody knows of pertinent links.
I'm experiencing this in FF3, Chrome for Windows and of course just to be special IE8 doesn't even seem to able to perform the conversion on 2011-10-04 whatsoever: I'm just getting an empty string in my application
Thanks in advance for any further insight or resources.
I ran into this concept, too. For anyone googling "Javascript dates dashes slashes" like I was, this is the clearest demonstration that I can think of as to what's going on here.
In short, slashes means local time zone, and dashes means UTC. Other answers has explanations regarding why.
<script type="text/javascript">
var
testB = new Date("2012/02/09"),
testC = new Date("2012-02-09");
alert(testB.toString());
alert(testC.toString());
alert(testC.toUTCString());
</script>
**Update:**It looks like there are several different standards at work here:
The EMCAScript < 5 standard allowed for dates in the standard IETF format, e.g. Sun Oct 03 2010. With these dates, the local timezone is assumed.
In ECMAScript 5, a limited version of the ISO 8601 standard is also allowed, e.g. 2010-10-03. The spec seems to say (perhaps following ISO 8601?) that in this case, the UTC timezone is assumed if one is not specified.
I haven't found a spec that says Date.parse can handle mm/dd/yyyy dates, but my browser (Chrome 14) clearly can, and probably other browsers can too. This appears to follow standard 1 above, assuming the local timezone. Given that it's not in the spec, however, I would recommend not using this version, as it's likely to be browser-dependent (and I have no idea whether 10-03-2010 would result in a different date if I had a European locale set on my browser).
There are a few issues with the native Date.parse function in most interpreters - I have often had timezone issues like the one you describe. So in general, I either use a library like Datejs or I write my own parsing functions. The DateTime module of the SIMILE AJAX library has a pretty good example function for parsing ISO-8601 dates (what you're referring to as euroStyleDate, plus an optional time component).
When setting dates, I generally use new Date() and then use the setUTC*() functions to set the different date elements to my desired precision. It's not perfect, but at least you're dealing with a clear timezone.

Javascript data parsing in IE vs other browsers... It seems kinda screwed up. What's the deal?

Firstly, when I say other browsers I really only mean Firefox because that's all I tested in.
Internet Explorer can parse a date followed by a single character as a proper date. Whereas Firefox behaves as I'd expect.
For example...
var dateString = new Date("1/1/2010f");
alert(dateString);
In IE it will alert...
Thu Dec 31 21:00:00 UTC-0900 2009
Whereas in FF is will spit out...
"Invalid Date"
I first noticed this using the jquery validation plug in.
http://docs.jquery.com/Plugins/Validation/Methods/date
It seems like it just subtracts some amount of hours off the actual date in IE when a character is appended. I've tested in IE6 and IE8.
Am I missing something?
It is implementation dependent.
When Date as a "constructor" is passed a string object, it tries to build a date with its parse method (Date.parse).
That method shall parse strings returned by Date.toString() and Date.toUTCString(), which both return formats varying with the implementation. And this is how the ECMAScript standard says it should be.
I remember reading this in "the Rhino book" (Tommy Flanagan's great javascript book).
In practice, it might very well turn out everyone except IE does it the same way, but I haven't tested thoroughly.
Also, it is a bit much if IE tries to parse whatever one throws at it and produces a Date object out of ascii soup.
Internet Explorer uses a different parsing mechanism, which may or may not be documented, and may be very broken in some or many cases.

Categories

Resources