When it comes to programming, working with dates can be tricky. Fortunately, however, most languages have done this difficult work and have a built-in date feature to help us. JavaScript is a useful feature to help with a lot of output, set the date.
The JavaScript Date Object
Start date The first thing you need to do in JavaScript is to initialize an object, and so on:
var New Date ();
This is good if we want to get the current date and time, but it does not help us much if we are planning to work in the past or future dates. In this example, we need to pass the date as an argument to the above code.
The problem
The question I want to discuss today is that for IE and Safari, it's about how the date is not working as expected, as shown below:
var New Date ("2011-02-07"); alert (d); Or:varnew Date ("2011-02-07t11:05:00"); alert (d);
If you run the above code snippet in a different browser, you will find the illegal date in your IE and safari south to return you. However, the browser, chrome and opera will output the correct date.
The solution
The problem is that you pass the specified date to the () object format. For some reason, don't ask me why, the above two browsers are not supported by the date format "YYYY-MM-DD" and therefore fail. I haven't managed to compile a definitive list of supported date formats, but I can tell you that the following format is absolutely supported for all browsers and suggests sticking to one of these to avoid errors:
- var d = New Date (2011, 01, 07); //yyyy, MM-1, DD
- var d = New Date (2011, 01, 07, 11, 05, 00); //yyyy, MM-1, DD, hh, MM, SS
- var d = new Date ("02/07/2011"); //"mm/dd/yyyy"
- var d = new Date ("02/07/2011 11:05:00"); //"mm/dd/yyyy hh:mm:ss"
- var d = new Date (1297076700000); //milliseconds
- var d = new Date ("Mon Feb 11:05:00 GMT"); //"" Day Mon dd yyyy
JavaScript new Date () error in IE browser NaN