【问题标题】:How do I convert years to months using moment.js?如何使用 moment.js 将年转换为月?
【发布时间】:2017-12-20 15:58:29
【问题描述】:

目前我的代码如下:

moment.duration(res.duration, "years").format("Y [years] M [months]"); //Input 0.08 outputs 0

当 res.duration

moment.duration(res.duration, 'months').format("M [months]"); //Input 0.08 outputs 0

但似乎还是不行。

知道如何完美地将 0.08 转换为 1 吗?

【问题讨论】:

  • 我错过了什么 - 0.08 指的是什么?
  • 所以我在我的数据库中以年为单位存储持续时间。因此,如果计算的持续时间是 1 个月,那么它将存储为 (1/12=0.08)。我将其存储到小数点后 2 位。但是为了向用户显示它,我希望它是 1(而不是 0.08),因为它更易于阅读。
  • moment.duration().format() 对你有用吗?
  • @ShimonBrandsdorfer 我认为 OP 正在使用 moment-duration-format 插件,将 format() 方法添加到持续时间。

标签: jquery node.js momentjs


【解决方案1】:

问题是0.08 年是不是 1 个月,它是0.96 月,所以你必须四舍五入。

不幸的是,moment-duration-format(我假设您正在使用)只能截断持续时间的值,将负整数传递给precision 选项。

可能的解决方案:

  1. 存储精度更高的值,而不是在小数点后四舍五入。这是一个使用0.080.08333333333333333 的实时示例。 (见month()toISOString()

var dur = moment.duration(0.08, "years");
console.log(dur.format('M [Months]'));
console.log(dur.months());
console.log(dur.toISOString());

// More decimal gives 1 month
dur = moment.duration(0.08333333333333333, "years");
console.log(dur.format('M [Months]'));
console.log(dur.months());
console.log(dur.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
  1. 使用时刻humanize()。您可以按照文档的Relative TimeRelative Time ThresholdsRelative Time Rounding 部分中的说明自定义输出。

moment.updateLocale('en', {
    relativeTime : {
        M:  "1 month",
        MM: "%d months"
    }
});

var dur = moment.duration(0.08, "years");
console.log(dur.humanize());
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    我认为你误解了 moment.duration 的作用:

    要创建持续时间,请使用时间长度(以毫秒为单位)调用 moment.duration()。 [...] 如果您想使用毫秒以外的度量单位创建时刻,您也可以传递度量单位。

    所以通过这样做:

    moment.duration(0.08, 'months')
    

    您正在创建 0.08 个月的持续时间。我认为你想要 0.08

     moment.duration(0.08, 'years')
    

    您也不能在持续时间内使用format,因此请手动执行此操作:

    var months = Math.round(moment.duration(0.08,"years").months());
    console.log(months,"month");
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"&gt;&lt;/script&gt;

    如果您真的想使用format,您可以将持续时间转换回片刻

    var dur = moment.duration(0.08,"years");
    console.log(moment.utc(dur.as('milliseconds')).format('M [Months]'));
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"&gt;&lt;/script&gt;

    在上面的例子中要注意的事情 - 它四舍五入。所以0.1 的值给出了2 months

    【讨论】:

      猜你喜欢
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多