Convert seconds to Date object in JavaScript

Without libraries

Number.prototype.toDate = function () {
    var seconds = Math.floor(this), hours = Math.floor(seconds / 3600);
    seconds -= hours * 3600;
    var minutes = Math.floor(seconds / 60);
    seconds -= minutes * 60;

    if (hours < 10) {hours   = "0" + hours;}
    if (minutes < 10) {minutes = "0" + minutes;}
    if (seconds < 10) {seconds = "0" + seconds;}

    var date = new Date();
    date.setHours(hours);
    date.setMinutes(minutes);
    date.setSeconds(seconds);
    return date;
}

220.toDate()

Use moment.js

moment().startOf('day').seconds(220).toDate()
comments powered by Disqus