Just for fun, looking for YouTube style timespans on YouTube posts.

Anyway, you get the idea.

Researched and found this thread with one answer, which I think is simple and elegant. Please read the comment below the answer because it might have some drawbacks pending on your environment [1].

function snowmanCarl(time1, time2) {
    var d = Math.abs(time2 - time1) / 1000; // delta
    var r = {}; // result
    var s = { // structure
        year: 31536000,
        month: 2592000,
        week: 604800, // uncomment row to ignore
        day: 86400, // feel free to add your own row
        hour: 3600,
        minute: 60,
        second: 1
    };

    Object.keys(s).forEach(function(key) {
        r[key] = Math.floor(d / s[key]);
        d -= r[key] * s[key];
    });

    // for example: {year:0,month:0,week:1,day:2,hour:34,minute:56,second:7}
    return r;
}

I wrapped it into another function ‘calcYoutubeStyleTimespan’ to get the result. For the time span less than 24 hours, I simplify as “a few hours”.

function calcYoutubeStyleTimespan(time1, time2) {
    let r = snowmanCarl(time1, time2);

    let youtubeTimespan = null;
    Object.keys(r).forEach(function(key) {
        if (!youtubeTimespan) {
            let diff = parseInt(r[key]);
            if (diff !== 0) {
                if (key === "hour" || key === "minute" || key === "second") {
                    youtubeTimespan = "a few hours ago";
                } else if (diff === 1) {
                    youtubeTimespan = diff + " " + key + " ago";
                } else {
                    youtubeTimespan = diff + " " + key + "s ago";
                }
            }
        }
    });

    return youtubeTimespan;
}

Cheers!

References:

  1. https://stackoverflow.com/questions/13903897/javascript-return-number-of-days-hours-minutes-seconds-between-two-dates