Introduction: In the same language JavaScript, in different browsers, there is a language compatibility problem, essentially because different browsers are supported by the language standards and implementation of the differences. This article will analyze this problem by creating a Date object based on the new date.
1. Problem raised, start time and end time space cannot pass value correctly
On the page, we used a time component to develop the time selection box, but found that it does not work properly under Firefox and that it works under Chrome. What is the problem?
2. Problem analysis
The results of the analysis revealed that the following code generated the problem:
var timestart = ' 2010-05-04 '; var timeend = ' 2015-04-01 '; var time1 = (timestart+ ' 00:00:00 '). toString (); var time2 = (timeen d+ ' 23:59:59 '). toString (); timestart = new Date (time1); timeend = new Date (time2);
The problem is that the new date (time1) constructor does not correctly generate a Date object with a value of Nan. Strange, where is the problem?
3. Performance on individual browsers
Performance under IE:
What to do under Firefox:
What to do under chrome:
The above analysis shows that this JavaScript script can be executed correctly under Chrome, but the error is reported in other browsers.
4. The right approach
The following are 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 the conversion of the default date format, a date string based on the '/' format, which is widely supported by various browsers, '-' the date string of the connection, then only works under Chrome.
5. Summary of Knowledge points
' 2015-05-04 ' is not available in each browser, using new Date (str) to correctly generate the Date object. The correct usage is ' 2015/05/05 '.
Browser compatibility issues with new Date () in JavaScript