Search code examples
javascriptdateluxon

Difference between two date in an human readable format


I have an object that rapresent the time difference between a date and now (I used Luxon):

{days: -0, hours: -15, minutes: -38, months: -0, seconds: -46.389, years: -0}

and I want to print that information in an human readable way. So, in this case:

difference is 15 h, 38 min, 46 s

So, I wouldn't consider numbers equals to 0 and the result should be sorted so years, months, days, hours, minutes, seconds. What is the smarter way to do that?


Solution

  • you can use something like this

    function toReadable(obj) {
        var names = {
            days: "d", hours: 'h', minutes: 'min', months: 'm', seconds: 's', years: 'y'
        }
        return Object.keys(obj).reduce((acc, v) => {
            if(obj[v] != 0) acc.push(Math.abs(Math.ceil(obj[v])) + ' ' + names[v]);
            return acc;
        }, []).join(', ')
    }