Convert string to DateTime Javscript


I have a string "2015-08-04 00:15:00", when trying to convert this to a DAteTime so I can use getHours(), getMinutes() etc, javscript seems to throw an error with Invalid Date.

The str string

function formatDate(date) {
        var str = "2015-08-04 00:15:00";
        var dateTime =new Date(str);
        var hours = dateTime.getHours();
        var minutes = dateTime.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        return dateTime.getMonth() + 1 + "/" + dateTime.getDate() + "/" + dateTime.getFullYear() + "  " + strTime;

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
The Javascript date constructor expects the dateString to be in the following format
See also
If you change your dateString to  
var str = "2015-08-04T00:15:00"; // NOTE THE 'T' BETWEEN DATE AND TIME

Open in new window

the code will work.
You need to ensure your date parameter is in the above format, if it is not you need to convert it or split your string into the various components and instantiate the Date object with the numeric values for year month day etc.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
wint100Author Commented:
I ended up using moment.js as the value is returned from a rest service that I don't control so it was easier to let moment do the work of parsing.

Julian HansenCommented:
You are welcome
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.