Created
September 29, 2012 15:47
-
-
Save kinopyo/3804414 to your computer and use it in GitHub Desktop.
Javascript: relative datetime
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
var relativeDate = function(date){ | |
if (navigator.appName === 'Microsoft Internet Explorer') return ''; | |
var unit = { | |
now: 'Now', | |
minute: '1 min', | |
minutes: ' mins', | |
hour: '1 hr', | |
hours: ' hrs', | |
day: 'Yesterday', | |
days: ' days', | |
week: '1 week', | |
weeks: ' weeks' | |
}; | |
var current = new Date(), | |
tweet = new Date(date), | |
diff = (((current.getTime() + (1 * 60000)) - tweet.getTime()) / 1000), | |
day_diff = Math.floor(diff / 86400); | |
if (day_diff == 0){ | |
if (diff < 60) return unit.now; | |
else if (diff < 120) return unit.minute; | |
else if (diff < 3600) return Math.floor(diff / 60) + unit.minutes; | |
else if (diff < 7200) return unit.hour; | |
else if (diff < 86400) return Math.floor(diff / 3600) + unit.hours; | |
else return ''; | |
} else if (day_diff == 1) { | |
return unit.day; | |
} else if (day_diff < 7) { | |
return day_diff + unit.days; | |
} else if (day_diff == 7) { | |
return unit.week; | |
} else if (day_diff > 7) { | |
return Math.ceil(day_diff / 7) + unit.weeks; | |
} else { | |
return ''; | |
} | |
} | |
// Usage: | |
relativeDate(new Date()) // return "1 min" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment