javascript 使用角度过滤器计算日期差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25635082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:46:28  来源:igfitidea点击:

Calculating date difference with angular filter

javascriptangularjsangularjs-scopeangular-filters

提问by zmanc

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.

我需要能够计算两天之间的差异(包括两天)并显示差异。理想情况下,这将通过角度过滤器进行,因此它可以在整个应用程序中使用。

回答by zmanc

JS Filter

JS过滤器

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.

HTML 来显示值。

<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>

回答by s1moner3d

Duplicate of 26649194

重复的26649194

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

角力矩可以解决问题!...和(非常)其他更多。

Using the amDifferencefilter:

使用amDifference过滤器:

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

以毫秒为单位获取两个日期之间的差异。参数是日期、单位和 usePrecision。日期默认为当前日期。例子:

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