Skip to content

Instantly share code, notes, and snippets.

@alash3al
Created December 31, 2015 22:07
Show Gist options
  • Save alash3al/4ad18cbcbdd48847d32d to your computer and use it in GitHub Desktop.
Save alash3al/4ad18cbcbdd48847d32d to your computer and use it in GitHub Desktop.
get the difference between two unix dates in the style of "x [second|minute|hour|month|year]s ago"
// timeDiff - get the difference between two "unix" dates
// version: 1.0.0
// author: Mohammed Al Ashaal
function timeDiff(t_new, t_old) {
t = {
second: 1,
minute: 1 * 60,
hour: 1 * 60 * 60,
day: 1 * 60 * 60 * 24,
week: 1 * 60 * 60 * 24 * 7,
month: 1 * 60 * 60 * 24 * 30,
year: 1 * 60 * 60 * 24 * 30 * 12
}
diff = t_new - t_old
if ( diff < t.minute ) {
return {
since: diff,
type: "second",
}
}
else if ( diff >= t.minute && diff < t.hour ) {
return {
since: Math.floor(diff / t.minute),
type: "minute",
}
}
else if ( diff >= t.hour && diff < t.day ) {
return {
since: Math.floor(diff / t.hour),
type: "hour"
}
}
else if ( diff >= t.day && diff < t.week ) {
return {
since: Math.floor(diff / t.day),
type: "day"
}
}
else if ( diff >= t.week && diff < t.month ) {
return {
since: Math.floor(diff / t.week),
type: "week"
}
}
else if ( diff >= t.month && diff < t.year ) {
return {
since: Math.floor(diff / t.month),
type: "month"
}
}
else if ( diff >= t.year ) {
return {
since: Math.floor(diff / t.year),
type: "year"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment