Skip to content

Instantly share code, notes, and snippets.

@Megabytemb
Last active November 11, 2015 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Megabytemb/074c9357efb874314cfd to your computer and use it in GitHub Desktop.
Save Megabytemb/074c9357efb874314cfd to your computer and use it in GitHub Desktop.
app.directive('dynamicTime', ['$timeout', '$log',
function ($timeout, $log) {
return {
restrict: 'E',
scope: {
time: '=',
prefix: '@',
suffix: '@'
},
controller: function ($scope) {
var update_dates = function () {
if ($scope.time) {
var time_delta = Date.daysBetween(new Date($scope.time), new Date());
if ($scope.prefix) {
time_delta = $scope.prefix + " " + time_delta;
}
if ($scope.suffix) {
time_delta = time_delta + " " + $scope.suffix;
}
$scope.last_update = time_delta;
}
$timeout(update_dates, 500);
};
update_dates();
},
template: '{{last_update}}'
};
}]);
Date.daysBetween = function (date_now, date_future) {
// get total seconds between the times
var delta = Math.abs(date_future - date_now) / 1000;
delta_orig = delta;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = Math.floor(delta % 60); // in theory the modulus is not required
if (delta_orig < 60) {
return seconds == 1 ? seconds + " sec" : seconds + " secs";
}
if (delta_orig < 60 * 60) {
return minutes == 1 ? minutes + " min" : minutes + " mins";
}
if (delta_orig < 24 * 60 * 60) {
return hours == 1 ? hours + " hour" : hours + " hours";
}
return days == 1 ? days + " day" : days + " days";
}
<dynamic-Time time="data.response.oldest_incident_sd.update_date_epoch*1000" suffix="old"></dynamic-Time>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment