Search code examples
javascriptjquerydatedate-conversion

Javascript String to Date Conversion using new Date()


Please find my code below to convert date in string format to date format.

var olddatetxt = "10/01/2014"; //October 1st 2014
var olddatearray = olddate.split("/"); //Values inside array are [10,01,2014]
var olddate = new Date(olddatearray [2], olddatearray [0], olddatearray [1]);

The problem here is the variable olddate is getting the value as

Sat Nov 1 00:00:00 UTC+0530 2014

What is the error here ? Im passing values of October month & why my result is November 1st ?


Solution

  • The problem is the Date takes month value as a 0 indexed value.

    month
    Integer value representing the month, beginning with 0 for January to 11 for December.

    var olddatetxt = "10/01/2014"; //October 1st 2014
    var olddatearray = olddatetxt.split("/"); //Values inside array are [10,01,2014]
    var olddate = new Date(olddatearray[2], olddatearray[0] - 1, olddatearray[1]);
    
    document.querySelector('#result').innerHTML = olddate;
    <div id="result"></div>