Skip to content

Instantly share code, notes, and snippets.

@alash3al
Created January 6, 2016 20:59
Show Gist options
  • Save alash3al/d6224512b0c38b556cda to your computer and use it in GitHub Desktop.
Save alash3al/d6224512b0c38b556cda to your computer and use it in GitHub Desktop.
Implementation of the "since x time ago" format, it starts from second to millennium ;-)
/*
* timeDiff, return the difference between two times "in seconds"
* in the format of "since x (second|minute|...)(s) ago" .
*
* @version v2.0
* @license MIT License
* @author Mohammed Al Ashaal <www.alash3al.xyz>
* @example `console.log(timeDiff(current_unix_timestamp, old_unix_timestamp))`
* @return Object
*/
function timeDiff(t_new, t_old){
var types = ["millennium", "century", "decade", "year", "month", "week", "day", "hour", "minute", "second"]
var diff = t_new - t_old
var res = {}
var t = {}
t.second = 1
t.minute = t.second * 60
t.hour = t.minute * 60
t.day = t.hour * 24
t.week = t.day * 7
t.month = t.day * 30
t.year = t.month * 12
t.decade = t.year * 10
t.century = t.decade * 10
t.millennium = t.century * 10
for ( var k in types ) {
if ( (diff / t[types[k]]) >= 1 ) {
res = {
type: types[k],
since: Math.floor(diff / t[types[k]]),
}
break
}
}
res.text = "since " + res.since + " " + res.type + "(s) ago"
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment