user1032531
user1032531

Reputation: 26281

Create JavaScript Date object from m/d/Y H:I:s

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);}

Upvotes: 1

Views: 988

Answers (2)

Greg Burghardt
Greg Burghardt

Reputation: 18783

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

Upvotes: 1

VisioN
VisioN

Reputation: 145368

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.

Upvotes: 4

Related Questions