Browser compatibility of new Date () in javascript, javascriptdate
Introduction: javascript in the same language has a language compatibility problem in different browsers. Essentially, different browsers support different language standards and implementations. This article will create a Date object based on new Date to analyze this problem.
1. the start time and end time space cannot pass the correct value when the problem is raised.
On the page, we used a time component to develop the Time Selection box, but found that it could not work normally in Firefox, and it could work normally in Chrome. Where is the problem?
2. Problem Analysis
The result analysis shows that the problem is caused by the following code:
var timestart = '2010-05-04';var timeend = '2015-04-01';var time1 = (timestart+' 00:00:00').toString();var time2 = (timeend+' 23:59:59').toString();timestart = new Date(time1);timeend = new Date(time2);
The problem is that the new Date (time1) constructor cannot correctly generate the Date object. Its value is NaN. Strange. Where is the problem?
3. Performance on various browsers
Execution in IE:
Execution in Firefox:
Execution in Chrome:
Through the above analysis, we can know that this javascript script can be correctly executed in Chrome, but an error is reported in other browsers.
4. correct practices
The following lists the correct practices:
var time1 = (timestart+' 00:00:00').toString(); var time2 = (timeend+' 23:59:59').toString(); timestart = new Date(Date.parse(str.replace(/-/g,"/"))).getTime(); timeend = new Date(Date.parse(str.replace(/-/g,"/"))).getTime();
The main change is to convert the default date format. The date String Based on the '/' format is widely supported by various browsers, it works normally only in chrome.
5. Knowledge Point Summary
'2017-05-04 'cannot be used by browsers to correctly generate Date objects using new Date (str. The correct usage is '2017/05 '.