Reputation: 650
Hoping you can help me out, I'm trying to work out why this parse date function that I wrote is not working for the 29th May 2014 (and possibly other dates)
function parseDate(dateString){
//Accepts DD/MM/YYYY HH:MM
var date = new Date();
date.setDate (parseInt(dateString.substr(0, 2), 10));
date.setMonth (parseInt(dateString.substr(3, 2), 10) - 1);
date.setYear (parseInt(dateString.substr(6, 4), 10));
date.setHours (parseInt(dateString.substr(11, 2), 10));
date.setMinutes (0);
date.setSeconds (0);
date.setMilliseconds (0);
return date;
}
$('#result').text(parseDate('29/05/2014 08:00'));
//Result Thu May 01 2014 08:00:00 GMT+1000 (EST)
A link to the fiddle is here: http://jsfiddle.net/2k4Ux/
Its probably something stupid but I just can't figure it out at the moment.
Upvotes: 0
Views: 280
Reputation:
You could do this :
function parseDate(dateString) {
var parts = dateString.match(/\d+/g);
return new Date(
parts[2], parts[1] - 1, parts[0], // date
parts[3], parts[4] // time
);
}
Upvotes: 2
Reputation: 3079
You should change the order of your operations, like this: http://jsfiddle.net/maximgladkov/m6sUM/1/
function parseDate(dateString){
//Accepts DD/MM/YYYY HH:MM
var date = new Date();
date.setYear (parseInt(dateString.substr(6, 4), 10));
date.setMonth (parseInt(dateString.substr(3, 2), 10) - 1);
date.setDate (parseInt(dateString.substr(0, 2), 10));
date.setHours (parseInt(dateString.substr(11, 2), 10));
date.setMinutes (0);
date.setSeconds (0);
date.setMilliseconds (0);
return date;
}
$('#result').text(parseDate('29/05/2014 08:00'));
Not all months have more than 28 days, so before you set year and month, Date object cannot determine, if the date is valid.
Upvotes: 3