I am trying to convert a string representing a date such as "07/13/2015 12:00AM" to a valid date object in javascript. Calling new Date("07/13/2015 12:00AM") yields an Invalid Date.
Any help is appreciated.
I am trying to convert a string representing a date such as "07/13/2015 12:00AM" to a valid date object in javascript. Calling new Date("07/13/2015 12:00AM") yields an Invalid Date.
Any help is appreciated.
Share Improve this question asked Aug 27, 2015 at 21:09 i_tropei_trope 1,6042 gold badges24 silver badges43 bronze badges 2- 1 @devlincarnate Java !== Javascript – TbWill4321 Commented Aug 27, 2015 at 21:16
- Downvotes without ments aint cool. – i_trope Commented Aug 28, 2015 at 19:21
3 Answers
Reset to default 5It seems that the date parser doesn't like having the AM/PM directly against the minutes/seconds.
Just a quick fix
var date = "07/13/2015 12:00AM";
date = date.substr(0, date.length-2) +' '+ date.substr(-2);
new Date(date);
This is a function that would turn your datetime strings to 24-Hrs format, and now it can be handled by Date()
function set24Hrs(d){
if (d.slice(-2) === "PM"){
var hrs = parseInt(d.slice(-7,-5))
var mins = d.slice(-4,-2)
hrs = hrs + 12
var dd = d.slice(0,9) + " " + hrs + ":" + mins;
return dd;
} else if(d.slice(-2) === "AM"){
return (d.slice(0, 16));
} else {
throw ("UNRECOGNIZED_FORMAT","set24Hrs() Received Unrecognized Formatted String");
}
}
So, you can just use like that:
c = new Date(set24Hrs(03/1/2015 3:00PM))
// returns: Sun Mar 01 2015 15:00:00 GMT+0200 (Egypt Standard Time)
Now you have a working solution, however if you have a lot of code to work with dates in Javascript, I remend to take a look at libraries like date.js And moement.js
You could strip the date and rebuild like:
var timeStr = "07/13/2015 12:00AM";
var dateFormat = /(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})([AP]M)/;
var dateArray = dateFormat.exec(timeStr);
var d = new Date(dateArray[3],parseInt(dateArray[1])-1,dateArray[2],parseInt(dateArray[4])-(dateArray[6] == 'AM' ? 12 : 0),dateArray[5]);
alert(d);