如何在 angularjs 中人性化持续时间?

How to humanize duration in angularjs?

我正在使用 momentjs and moment-duration-formatY M D HH:mm:ss 格式显示持续时间,具体取决于持续时间(如果它包括年、月、日、小时、分钟和秒),并在此字段上使用 ngTable 排序和过滤器。

代码

  $scope.getTableDataDuration = function(item) {
      if (angular.isDefined(item) && item != null) {
          var tmp = "";
          if (item > 31536000) { //year
              tmp = moment.duration(item, "year").format("Y M D h:mm:s");
              return tmp;
          } else if (item > 2628000) { //month
              tmp = moment.duration(item, "month").format("M D h:mm:s");
              return tmp;
          } else if (item >= 86400) { //day
              tmp = moment.duration(item, "days").format("D h:mm:s");
              return tmp;
          } else if (item < 60) {
              return item;
          } else if (item < 3600) { //minute
              tmp = moment.duration(item, "minutes").format("h:mm:s");
              return tmp;
          }
      }
      return;
  }

Plunker link

更新

例如:

duration in seconds 331 should show 05:51
duration in seconds 7245 should show 02:01:25 
similarly till years

给定持续时间,我需要将其人性化,类似于上面的示例

我认为您误解了文档。我个人没有用moment-duration,但是从GitHub上的文档来看,你想用的好像是这个

  moment.duration(99544, "seconds").format("D h:mm:s");

它通知 Duration 插件,输入的数字以秒为单位,确实如此。然后通过提供的格式字符串对其进行格式化。

看这个例子https://github.com/jsmreese/moment-duration-format#weeks

他在这里使用 moment.duration(123, "days").format("w W", 2); 基本上是说 "I have 123 days and I want to convert it to number of weeks"