Skip to content

Instantly share code, notes, and snippets.

@aosalias
Created January 6, 2015 21:31
Show Gist options
  • Save aosalias/19f9810d476c38756727 to your computer and use it in GitHub Desktop.
Save aosalias/19f9810d476c38756727 to your computer and use it in GitHub Desktop.
Time diff to human readable - Javascript
function formatTimeDiff(diff) {
var signifcants = 2,
human = '',
current,
times = [['year', 31536000],
['month', 2628000],
['week', 606461],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1]];
times.every( function(tup){
var unit = tup[0],
time = tup[1];
if (signifcants == 1) { human += ' ' };
current = Math.floor(diff / time >= 1);
if (current > 0) {
human += current > 1 ? current + ' ' + unit : '1 ' + unit;
signifcants -= 1;
diff = diff % time;
}
return signifcants != 0;
});
return human;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment