I have implemented a unique custom angular.js filter for formatting datetime objects:
function relativeTimeFilter()
{
return function (dateObj) {
return getRelativeDateTimeString(dateObj);
};
}
function getRelativeDateTimeString(dt)
{
if(!dt) return "undefined ago";
var delta = dt.getSeconds();
if (delta < 0) return "not yet";
if (delta < 1 * 60) return delta == 1 ? "one second ago" : delta + " seconds ago";
if (delta < 2 * 60) return "a minute ago";
if (delta < 45 * 60) return Math.floor(delta/60) + " minutes ago";
if (delta < 90 * 60) return "an hour ago";
if (delta < 24 * (60*60)) return Math.floor(delta/60/60) + " hours ago";
if (delta < 48 * (60*60)) return "yesterday";
if (delta < 30 * (24 * (60*60))) return Math.floor(delta/60/60/24) + " days ago";
if (delta < 12 * (30 * (24 * (60*60))))
{
var months = Math.floor(delta/60/60/24/30);
return (months <= 1) ? "one month ago" : (months + " months ago");
}
else
{
var years = Math.floor(delta/60/60/24/365);
return (years <= 1) ? "one year ago" : (years + " years ago");
}
}
module.filter("relativetime", relativeTimeFilter);
While using this filter, I want the relative time to be continuously updated. For example, one second ago
should update to 2 seconds ago
after one second passes.
Initially, I tried applying setInterval in my controller function to trigger the filter at regular intervals:
setInterval(function() {$scope.$apply()}, 1000) // placed in controller function
However, this approach did not work as expected. Do you have any suggestions on how to achieve this periodic update with the filter?