Last active
May 17, 2017 12:00
-
-
Save kmcconnell/1f9f681b6dc1ef44f4787777f0201062 to your computer and use it in GitHub Desktop.
Render time interval in easy-to-read string.
This file contains 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
/** | |
* Compares two datetime values and returns a human-readable interval in past or | |
* future tense. | |
* | |
* @param {string|number|Date} start The first (from) datetime to use in comparison. | |
* @param {string|number|Date} stop The second (to) datetime to use in comparison. | |
* | |
* @example "6 seconds ago" | |
* | |
* @return {string} The interval statement. | |
*/ | |
function interval_duration(start, stop) | |
{ | |
/** | |
* @see convert_to_date_object https://gist.github.com/kmcconnell/f4931ee58edff1f593ee1f1a7f0ea51a | |
*/ | |
start = convert_to_date_object(start); | |
stop = convert_to_date_object(stop); | |
var time_formats = [ | |
[60, 'seconds', 1], | |
[120, '1 minute ago', '1 minute from now'], | |
[3600, 'minutes', 60], | |
[7200, '1 hour ago', '1 hour from now'], | |
[86400, 'hours', 3600], | |
[172800, 'yesterday', 'tomorrow'], | |
[604800, 'days', 86400], | |
[1209600, 'last week', 'next week'], | |
[2419200, 'weeks', 604800], | |
[4838400, 'last month', 'next month'], // 60*60*24*7*4*2 | |
[29030400, 'months', 2419200], | |
[58060800, 'last year', 'next year'], | |
[2903040000, 'years', 29030400], | |
[5806080000, 'last century', 'next century'], | |
[58060800000, 'centuries', 2903040000] | |
]; | |
var seconds = (stop - start) / 1000, token = 'ago', key = 1; | |
if (seconds === 0) { | |
return 'just now'; | |
} | |
if (seconds < 0) { | |
seconds = Math.abs(seconds); | |
token = 'from now'; | |
key = 2; | |
} | |
var itx = 0, format; | |
while (format = time_formats[itx++]) { | |
if (seconds < format[0] && typeof(format[2]) == 'string') { | |
return format[key]; | |
} | |
if (seconds < format[0]) { | |
return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment