Stefano Maglione
Stefano Maglione

Reputation: 4150

Convert string by javascript date function

I'm try to initialize a new date object but I don't understand why returns me ever Invalid Date.

var dateString= this.get("created_at");
    var dataParts = dateString.split(' ');
    var timeParts = dataParts[3].split(':');

    //console.log(dataParts);-->["Fri", "May", "09", "17:45:54", "+0000", "2014"] 
    //console.log(timeParts);-->["17", "45", "54"]


    var year=dataParts[5];
    var month=dataParts[1];
    var day=dataParts[2];
    var hour=timeParts[0];
    var minute=timeParts[1];
    var second=timeParts[2];


    var date = new Date(year,month,day,hour,minute,second);


    console.log(date);

Upvotes: 0

Views: 67

Answers (1)

Andy G
Andy G

Reputation: 19367

var date = new Date(year,month,day,hour,minute,second);

using this constructor the month needs to be a number, not "May".

Note also that months begin at 0 for January, so May is 4.

Alternatively, construct the date as a string: new Date("May 09, 2014 17:45:54") from the parts that you have. (You won't have to split the time or lookup the month-number.)

Upvotes: 3

Related Questions