Browser compatibility of the Date function new Date () in javascript, javascriptdate

Source: Internet
Author: User

Browser compatibility of the Date function new Date () in javascript, javascriptdate

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-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 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(time1.replace(/-/g,"/"))).getTime(); timeend = new Date(Date.parse(time2.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-09-05 'cannot be used by browsers to correctly generate Date objects using new Date (str. The correct usage is '2017/06 '.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.