1

I am trying to create a JavaScript Date object from a from m/d/Y H:I:s string. Below is my attempt. It works fine without the H:I:s, but does not work with it. How do I create JavaScript Date object from m/d/Y H:I:s?

var dt=' 5/5/1964 11:13:00 '; var valid=false; dt = dt.replace(' ',' '); //Get rid of double spaces dt.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); //Trim string dt=dt.split(' '); var d=(dt[0])?dt[0].split('/'):[]; var t=(dt[1])?dt[1].split(':'):[]; if (d.length === 3) { d=[d[2],d[1]-1,d[0]]; //Change to YMD and month to 0 to 11 //var date=new Date.apply(null, d.concat(t)); //doesn't work dt = d.concat(t).join(); console.log(dt); var date=new Date(dt); console.log(date); if ( Object.prototype.toString.call(date) === "[object Date]" && !isNaN( date.getTime() )) { // it is a date and is valid. date.valueOf() could also work instead of date.getTime() valid=true; } } if(valid){ doSomethingWithDate(date);} 

2 Answers 2

4

There is no real need in special parsing of the string, as the Date class constructor (internally Date.parse) can parse the given format automatically:

var date = new Date(' 5/5/1964 11:13:00 '); console.log(date); // e.g. Tue May 05 1964 11:13:00 GMT+0100 (BST) 

See more examples of the formats in MDN.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks VisioN. Works with all common browser?
@user1032531 Should do, according to the standards.
1

Running new Date(" 5/5/1964 11:13:00 ") worked just fine for me.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.