Last active
August 29, 2015 14:17
-
-
Save ivanbanov/0f7a92142d869d785b5e to your computer and use it in GitHub Desktop.
Script to calculate how older is some date
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
;(function(win) { | |
'use strict'; | |
/* | |
* CONSTRUCTOR | |
*/ | |
function DateDiff(date) { | |
this.date = new Date(date); | |
this.dateNow = new Date(); | |
} | |
/* | |
* PUBLIC | |
*/ | |
DateDiff.prototype = { | |
constructor: DateDiff, | |
minutes: function() { | |
return toInt((this.dateNow - this.date) / 36e5 * 60); | |
}, | |
hours: function() { | |
return toInt(this.minutes(this.dateNow, this.date) / 60); | |
}, | |
days: function() { | |
return toInt(this.hours(this.dateNow, this.date) / 24); | |
}, | |
weeks: function() { | |
return toInt(this.days(this.dateNow, this.date) / 7); | |
}, | |
months: function() { | |
var d1Y = this.dateNow.getFullYear(), | |
d2Y = this.date.getFullYear(), | |
d1M = this.dateNow.getMonth(), | |
d2M = this.date.getMonth(); | |
return toInt((d1M + 12 * d1Y) - (d2M + 12 * d2Y)); | |
}, | |
time: function() { | |
var minuteDiff = this.minutes(this.dateNow, this.date), | |
hourDiff = this.hours(this.dateNow, this.date), | |
dayDiff = this.days(this.dateNow, this.date), | |
weekDiff = this.weeks(this.dateNow, this.date), | |
monthDiff = this.months(this.dateNow, this.date); | |
return minuteDiff <= 60 ? text('minute', minuteDiff) | |
: hourDiff <= 24 ? text('hour', hourDiff) | |
: dayDiff <= 7 ? text('day', dayDiff) | |
: weekDiff <= 4 ? text('week', weekDiff) | |
: text('month', monthDiff); | |
} | |
} | |
/* | |
* PRIVATE | |
*/ | |
function toInt(n) { | |
return parseInt(Math.abs(n)); | |
} | |
function text(type, number) { | |
var text = '', | |
n = number > 1 ? false : true; | |
switch (type) { | |
case 'minute': | |
text = n ? 'minute' : 'minutes' | |
break; | |
case 'hour': | |
text = n ? 'hour' : 'hours' | |
break; | |
case 'day': | |
text = n ? 'day' : 'days' | |
break; | |
case 'week': | |
text = n ? 'week' : 'weeks' | |
break; | |
case 'month': | |
text = n ? 'month' : 'months' | |
break; | |
} | |
return number + ' ' + text + ' ago'; | |
} | |
/* | |
* GLOBAL | |
*/ | |
win.DateDiff = DateDiff; | |
})(window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment