I’ve been banging my head over this one all day. No matter how I initialize a Javascript Date I cannot seem to get a valid Date object… I’m assuming the Date is invalid and not working properly by inspecting it with Chrome’s debugger, which has the value ‘__proto__: Invalid Date’.
I’ve tried all of the following:
var d = new Date();
var d = new Date('2012-10-08');
var d = new Date('2012-10-08 00:00:00');
var d = new Date(Date('2012-10-08'));
var d = new Date(Date.parse('2012-10-08'));
var d = new Date(2012,10,08);
var d = new Date("October 13, 1975 11:13:00");
Along with countless other attempts.
This is presenting a problem in iOS where I’m trying to get values from these Date objects but every function just returns NaN. I’d prefer to avoid having to use external libraries or have to convert YYYY-MM-DD format into any other format since I’m trying to get this to work with an HTML5 input type=”date” with minimal code for a mobile site.
Essentially this boils down to: What are the parameters that make a Date object valid?!
Do not trust the Date object to parse strings, you must do it manually. Given the format
2012-10-08,You may want to do some validation of the input string and the resulting date object, the above just shows the conversion.
Edit
BTW, the only string format that seems to be parsed consistently in all browsers is the US-specific
month/date/yearformat. There is no specification to support its use, nor is there any reason to believe browsers will continue to support it other than pragmatism and “legacy” reasons.For the vast majority of regions, ‘2/3/2012’ is interpreted as 2 March, so getting 3 February might be unexpected.
Once older versions of IE are no longer in use (probably a few years yet), it should be safe to use the ISO8601 extended format per ECMA-262. However, even browsers that support it are inconsitent. e.g given:
Firefox 15 returns ‘Invalid Date’, IE 9 and Chrome 22 return a date object for 1 March, 2011.