Home  >  Article  >  Web Front-end  >  Browser compatibility issues with date function new Date() in javascript_javascript skills

Browser compatibility issues with date function new Date() in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:40:521304browse

The same language, JavaScript, has language compatibility issues in different browsers. Essentially, this is due to the fact that 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 problem is that the start time and end time space cannot transfer values ​​correctly

In the page, we used a time component to develop the time selection box, but found that it did not work properly under Firefox, but it ran normally under Chrome. What's the problem?

2. Problem Analysis

The result analysis found that the problem is caused by the following code:

var timestart = '2010-05-04';
var timeend = '2015-09-05';
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 a Date object, and its value is NaN. Strange, what is the problem?

3. Performance on various browsers

Execution under IE:

Execution under Firefox:

Execution under Chrome:

Through the above analysis, it can be known that this javascript script can be executed correctly under Chrome, but an error is reported under other browsers.

4. Correct approach

The correct approach is listed below:

 var time1 = (timestart+' 00:00:00').toString();
 var time2 = (timeend+' 23:59:59').toString();
 timestart = new Date(Date.parse(time1.replace(/-/g,"/"))).getTime();
 timeend = new Date(Date.parse(time2.replace(/-/g,"/"))).getTime();

The main change is the conversion of the default date format. The date string based on the '/' format is widely supported by various browsers. The date string connected with '-' is only available in It works fine under chrome.

5. Summary of knowledge points

'2015-09-05' cannot be used by various browsers to correctly generate date objects using new Date(str). The correct usage is '2015/09/06'.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn