Created
January 6, 2016 20:59
-
-
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 ;-)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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