简体   繁体   English

如何使用Moment.js在几周内获得持续时间?

[英]How to get duration in weeks with Moment.js?

I use moment.js to format durations in human readable format. 我使用moment.js来格式化人类可读格式的持续时间。
For example ( d is a Date object): 例如( dDate对象):

moment(d).subtract("days", 3).from(d)  // returns "3 days ago"

Now I would like to get "2 weeks ago" but the code below returns the durations in days 现在我想“2周前”,但下面的代码会返回以天为单位的持续时间

moment(d).subtract("weeks", 2).from(d) // returns "14 days ago" i/o "2 weeks ago"

How can I get "2 weeks ago" with moment.js ? 我如何用moment.js获得“2周前”?

You can do this pretty easily with a custom callback function. 您可以使用自定义回调函数轻松完成此操作。

moment.relativeTime.dd = function (number) {
    // round to the closest number of weeks
    var weeks = Math.round(number / 7);
    if (number < 7) {
        // if less than a week, use days
        return number + " days";
    } else {
        // pluralize weeks
        return weeks + " week" + (weeks === 1 ? "" : "s"); 
    }
}

http://jsfiddle.net/timrwood/sWsXQ/ http://jsfiddle.net/timrwood/sWsXQ/

Use the new updateLocale() . 使用新的updateLocale()

Moment.js has been updated again so the preferred method is the following: Moment.js已经再次更新,因此首选方法如下:

moment.updateLocale('en', {

  relativeTime : {
    future: 'in %s',
    past:   '%s ago',
    s:      'a few seconds',
    m:      'a minute',
    mm:     '%d minutes',
    h:      'an hour',
    hh:     '%d hours',
    d:      'a day',
    dd:     function(number) {
              if (number < 7) {
                return number + ' days'; // Moment uses "d" when it's just 1 day.
              }
              else {
                var weeks = Math.round(number / 7);
                return weeks + ' ' + (weeks > 1 ? 'weeks' : 'week');
              }
            },
    M:      'a month',
    MM:     '%d months',
    y:      'a year',
    yy:     '%d years'
  }

});

Thanks to @timrwood and @gahen for their answers. 感谢@timrwood@gahen的回答。

I'm in the works to get Moment updated so that you can override just a single relativeTime object, like dd , instead of having to provide all of the objects. 我正在努力让Moment更新,这样你就可以只覆盖一个 relativeTime对象,比如dd ,而不是必须提供所有对象。

The GitHub Issue is here , so give it a thumbs up if you'd like to do something like this instead: GitHub问题在这里 ,所以如果你想做这样的事情,请竖起大拇指:

moment.updateLocale('en', {

  relativeTime : {
    dd: function(number) {
          if (number < 7) {
            return number + ' days'; // Moment uses "d" when it's just 1 day.
          }
          else {
            var weeks = Math.round(number / 7);
            return weeks + ' ' + (weeks > 1 ? 'weeks' : 'week');
          }
        }
  }

});

I can't comment on the previous answer but I wanted to leave an updated answer (based on timrwood 's) 我无法评论之前的答案,但我想留下更新的答案(基于timrwood的答案)

moment.locale('en', {
  relativeTime : {
    future: "in %s",
    past:   "%s ago",
    s:  "seconds",
    m:  "a minute",
    mm: "%d minutes",
    h:  "an hour",
    hh: "%d hours",
    d:  "a day",
    dd: function (number) {
      var weeks = Math.round(number / 7);
      if (number < 7) {
        // if less than a week, use days
        return number + " days";
      } else {
        // pluralize weeks
        return weeks + " week" + (weeks === 1 ? "" : "s"); 
      }
    },
    M:  "a month",
    MM: "%d months",
    y:  "a year",
    yy: "%d years"
  }
});

$window.moment.relativeTimeThreshold('d', 340); // if you want weeks instead of months, otherwise put a 28 or so.

The documentation lists the rules for creating those strings (under "Humanize time from another moment"). 文档列出了创建这些字符串的规则(在“从另一时刻开始人性化时间”)。 While you can modify the strings by changing moment.relativeTime , this is limited to the text that is displayed around the number, ie you can't change days to weeks. 虽然您可以通过更改moment.relativeTime来修改字符串,但这仅限于在数字周围显示的文本,即您不能将天数更改为几周。

You'll have to extend moment.js or write some custom code to implement this functionality. 您必须扩展moment.js或编写一些自定义代码来实现此功能。

sharing and hoping still useful: 分享和希望仍然有用:

var aPastDate = moment().subtract(5,'months');
var now = moment();


moment.fn.durationInWeeks = function (fromDate, toDate) {

   var weeks =  toDate.diff( fromDate, 'weeks' );
   return weeks + ' weeks ago'; //your own format

}

moment().durationInWeeks(aPastDate,now);

//"21 weeks ago"

improving on @vinjenzo's answer, when you need date diff in weeks, you will most likely encounter days returned: 改进@ vinjenzo的答案,当你需要几周的日期差异时,你很可能会遇到几天的回复:

var aPastDate = moment().subtract(5,'months');
var aPastDay = moment().subtract(6,'days');
var now = moment();

moment.fn.durationInWeeks = function(fromDate, toDate) {

    var days    = toDate.diff(fromDate, 'days');    
    var weeks   = toDate.diff(fromDate, 'weeks');

    if (weeks === 0) {
        return days + ' ' + (days > 1 ? 'days' : 'day');
    } else {
        return weeks + ' ' + (Math.round(days / 7) > 1 ? 'weeks' : 'week');
    }

}

moment().durationInWeeks(aPastDate,now); // 21 weeks
moment().durationInWeeks(aPastDay,now);  // 6 days

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM