如何使用Moment.js在几周内获得持续时间? [英] How to get duration in weeks with Moment.js?

查看:156
本文介绍了如何使用Moment.js在几周内获得持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 moment.js 来格式化人类可读格式的持续时间。

例如( d 日期对象):

I use moment.js to format durations in human readable format.
For example (d is a Date object):

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

现在我想得到2周前,但下面的代码返回以天为单位的持续时间

Now I would like to get "2 weeks ago" but the code below returns the durations in days

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

如何使用 moment.js 获取2周前 ?

How can I get "2 weeks ago" with moment.js?

推荐答案

您可以使用自定义回调函数轻松完成此操作。

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/

这篇关于如何使用Moment.js在几周内获得持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆