Skip to content

Instantly share code, notes, and snippets.

@mcraz
Created April 27, 2014 16:13
Show Gist options
  • Save mcraz/11349449 to your computer and use it in GitHub Desktop.
Save mcraz/11349449 to your computer and use it in GitHub Desktop.
Get time difference in human readable format
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";
}
@sourovroy
Copy link

Simple but useful, Thanks

@Lewiscowles1986
Copy link

Suggested adjustment, Requires you to pass in dates in correct order. If you use call after sorting, it should always give you the right result, presuming you have two results. Could look even better in TypeScript using modern JS like spread, but then it would need to own or receive a sorting method.

function timeSince(date1, date2) {

    var seconds = Math.floor((date2 - date1) / 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";
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment