Converting a SQL DATETIME to a JavaScript Date

It should come as no surprise to anyone who has developed for multiple browsers that each one has its own quirks when it comes to enforcing standards, whether they be CSS, HTML5, or even JavaScript. I have been working on some JavaScript that will take a date (in the DATETIME format) from SQL Server and create a new JavaScript Date object using this date. In doing most web development, I have been using Chrome to test the pages first because I find Chrome’s developer tools much better than those with Internet Explorer, even though the site will eventually have to be compatible with IE 8+.

Apparently, when taking a SQL DATETIME (which is in the format “yyyy-mm-dd hh:mm:ss.ms”) string and creating a new JS Date, Chrome will take it directly, but IE is more strict. IE enforces the JavaScript standard, and simply doesn’t recognize the DATETIME format as being a valid date. The way I solved this was to parse the DATETIME string by splitting it into arrays and instantiating the JS Date object by using the “new Date(year, month, day, hour, minute, second, millisecond)” syntax.

Below is a function that will take a string in the SQL DATETIME format and will return a JS Date object:

function sqlToJsDate(sqlDate){
    //sqlDate in SQL DATETIME format ("yyyy-mm-dd hh:mm:ss.ms")
    var sqlDateArr1 = sqlDate.split("-");
    //format of sqlDateArr1[] = ['yyyy','mm','dd hh:mm:ms']
    var sYear = sqlDateArr1[0];
    var sMonth = (Number(sqlDateArr1[1]) - 1).toString();
    var sqlDateArr2 = sqlDateArr1[2].split(" ");
    //format of sqlDateArr2[] = ['dd', 'hh:mm:ss.ms']
    var sDay = sqlDateArr2[0];
    var sqlDateArr3 = sqlDateArr2[1].split(":");
    //format of sqlDateArr3[] = ['hh','mm','ss.ms']
    var sHour = sqlDateArr3[0];
    var sMinute = sqlDateArr3[1];
    var sqlDateArr4 = sqlDateArr3[2].split(".");
    //format of sqlDateArr4[] = ['ss','ms']
    var sSecond = sqlDateArr4[0];
    var sMillisecond = sqlDateArr4[1];

    return new Date(sYear,sMonth,sDay,sHour,sMinute,sSecond,sMillisecond);
}

Leave a Reply