Doppu Doppu - 3 months ago 8
jQuery Question

How convert timestamp and put in a <input type="date">?

I have a variable that contains timestamp value that I have calculated first. I need to convert timestamp variable in a date and put the date in my:

<input type="date" id="topic_date">


Anyone can help me?

Answer

Try the following, parsing the timestamp into a date object first, after converting to milliseconds from seconds:

function lpad(str, length) {
    var lengthDiff = length - str.length;
    while(lengthDiff > 0) {
        str = '0' + str;
        lengthDiff--;
    }
    return str;
}

var parsedTimestamp = new Date(timestamp * 1000);
document.getElementById('topic_date').value = parsedTimestamp.getFullYear() + '-' + lpad(parsedTimestamp.getMonth(), 2) + '-' + lpad(parsedTimestamp.getDate(), 2);
Comments