c.k c.k - 4 months ago 14
jQuery Question

Convert yyyy-mm-dd hh:mm:ss format to time ago

I have this date & hour format

2016-03-07 15:13:49
. And I would like to display it like 1 minute ago, 1 hour ago or 1 year ago depending on how long is the date from now.

Answer

You need to convert your date format to js date object and then you can use the timeSince function from this answer

var date = new Date('2016-03-07T15:13:49')

document.write("js date: " + date + "<br><br>");
document.write("timesince: ");

document.write(timeSince(date));

function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
        return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
}

Comments