Skip to content

Instantly share code, notes, and snippets.

@waaronking
Created June 23, 2015 22:39
Show Gist options
  • Save waaronking/a777377712aa7804d7de to your computer and use it in GitHub Desktop.
Save waaronking/a777377712aa7804d7de to your computer and use it in GitHub Desktop.
Calculates times between two dates
/* TEMPORARY: Returns time string between two dates in days, hours, minutes, and seconds */
var timeBetweenTwoDates = function(date1, date2) {
var seconds = Math.round((date1 - date2)/1000); //seconds
return calculateTime(seconds);
};
/* TEMPORARY: Calculates time between two dates. TO BE REPLACED WITH BETTER i18n supported SOLUTION */
var calculateTime = function(seconds) {
var seconds = seconds || 0
, minutes = 0
, hours = 0
, days = 0
, years = 0;
if (seconds > 59) {
minutes = Math.floor(seconds / 60); // minutes
seconds = Math.floor(((seconds / 60) % 1) * 60);
if (minutes > 59) {
hours = Math.floor(minutes / 60); // hours
minutes = Math.floor(((minutes / 60) % 1) * 60);
if (hours > 23) {
days = Math.floor(hours / 24); // days
hours = Math.floor(((hours / 24) % 1) * 24);
if (days > 365) {
years = Math.floor(days / 365); // years
days = Math.floor(((days / 365) % 1) * 365);
}
}
}
} else {
seconds = Math.floor(seconds);
}
if (years) {
return years + " year" + ((years > 1) ? "s" : "") + " ago";
}
if (days) {
return days + " day" + ((days > 1) ? "s" : "") + " ago";
}
if (hours) {
return hours + " hour" + ((hours > 1) ? "s" : "") + " ago";
}
if (minutes) {
return minutes + "m" + " ago";
}
return seconds + "s" + " ago";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment