Skip to content

Instantly share code, notes, and snippets.

@klihelp
Last active September 18, 2015 07:00
Show Gist options
  • Save klihelp/8b2ecf243eed985d8d09 to your computer and use it in GitHub Desktop.
Save klihelp/8b2ecf243eed985d8d09 to your computer and use it in GitHub Desktop.
Get elapsed time, time ago, supports timezone
/**
* Get elapsed time, time ago, supports timezone
* @param integer time --- string | unix timestamp
* @param strings --- string | array
* @return string elapsed time
*/
function(datetime, strings, elative_to) {
if (arguments.length) {
var datetime = typeof datetime !== 'string' ? datetime : new Date(datetime)
} else {
var datetime = new Date()
}
if (Object.prototype.toString.call(strings) !== '[object Array]' || strings.length !== 7) {
if (typeof strings == 'string' && strings == 'short') {
var strings = [
'<1m',
'~1m',
'm',
'~1h',
'h',
'~1d',
'd'
]
} else {
var strings = [
'Less than a minute ago',
'About a minute ago',
' minutes ago',
'About an hour ago',
' hours ago',
'1 day ago',
' days ago'
]
}
}
var relative_to = typeof relative_to == 'undefined' || !relative_to ? new Date() : new Date(relative_to)
var delta = parseInt((relative_to.getTime() - datetime) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta < 60) {
return strings[0];
} else if (delta < 120) {
return strings[1];
} else if (delta < (60 * 60)) {
return (parseInt(delta / 60)).toString() + strings[2];
} else if (delta < (120 * 60)) {
return strings[3];
} else if (delta < (24 * 60 * 60)) {
return 'About ' + (parseInt(delta / 3600)).toString() + strings[4];
} else if (delta < (48 * 60 * 60)) {
return strings[5];
} else {
return (parseInt(delta / 86400)).toString() + strings[6];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment