Calculating date difference with angular filter

风格不统一 提交于 2019-12-30 10:48:13

问题


I needed to be able to calculate the difference between two days, inclusive, and display the difference. Ideally this would be via an angular filter so it can be used all over the application.


回答1:


JS Filter

generalFilters.filter('dateDiff', function () {
  var magicNumber = (1000 * 60 * 60 * 24);

  return function (toDate, fromDate) {
    if(toDate && fromDate){
      var dayDiff = Math.floor((toDate - fromDate) / magicNumber);
      if (angular.isNumber(dayDiff)){
        return dayDiff + 1;
      }
    }
  };
});

HTML to display the value.

<div class="field-value">{{entry.toStr | dateDiff:entry.fromStr}} <ng-pluralize count="entry.toStr | dateDiff:entry.fromStr" when="{1:'Day', other: 'Days'}"></ng-pluralize></div>



回答2:


Duplicate of 26649194

angular-moment does the trick! ...and (very) else more.

Using the amDifference filter:

Get the difference between two dates in milliseconds. Parameters are date, units and usePrecision. Date defaults to current date. Example:

<span>Difference: {{ dateFrom | amDifference : dateTo : 'days' }} days</span>


来源:https://stackoverflow.com/questions/25635082/calculating-date-difference-with-angular-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!