mustapha george mustapha george - 2 months ago 9
Javascript Question

js date object based on strings

I want to make a js date object based on strings in format YYYYMMDD and HHMMSS.

function makeTimeStamp(myDate, MyTime){
// myDate format YYYYMMDD
// myTime format HHMMSS
var YYYY = myDate.substring(0, 3);
var MM = myDate.substring(4, 5);
var DD = myDate.substring(6,7);

var HH = myTime.substring(0,1);
var MM = myTime.substring(2,3);
var SS = myTime.substring(4,5);
jsDate =
}

Answer

If you meant to be creating a Date object for given year, month, day, hours, minutes and seconds, you can use new Date(year, month - 1, day, hours, minutes, seconds) to create a Date instance for it. Note that the month is 0 based, January is 0, February 1, etc. Hence the MM - 1;

function stringToDate(myDate, myTime){
    // myDate format YYYYMMDD
    // myTime format HHMMSS
    var YYYY = myDate.substr(0, 4);
    var MM = myDate.substr(4, 2);
    var DD = myDate.substr(6, 2);

    var HH = myTime.substr(0, 2);
    var mm = myTime.substr(2, 2);
    var SS = myTime.substr(4, 2);

    var jsDate = new Date(YYYY, MM - 1, DD, HH, mm, SS);
    return jsDate;
}

// returns a Date object for given date and time
var jsDate = stringToDate("20110818", "191500");
// returns 1313687700000
var timestamp = jsDate.getTime();

Note that I'm using string.substr(start_position, length) as you can easily see the length of the returned value.