【问题标题】:Moment.js returning wrong date (one year ahead)Moment.js 返回错误的日期(提前一年)
【发布时间】:2022-01-11 20:50:47
【问题描述】:

我正在运行一些测试,但在 Moment.js 上遇到了问题

我数据库中的日期是2001-06-06T00:00:00.000+00:00。

我使用了Age: moment(user.dateOfBirth).toNow(true),而我得到了"Age": "21 years",而它显然应该是20。

dateOfBirth 属性在我的架构中设置为日期。我填写为2001-06-06。

我也尝试使用 .diff 并得到一个随机数。日期格式有问题吗?

谢谢。

【问题讨论】:

    标签: node.js date momentjs


    【解决方案1】:

    toNow 给出近似值,它正在四舍五入。 您可以使用的是持续时间。

    const dateOfBirth = "2001-06-06";
    const age1 = moment("2001-06-06", "yyyy-mm-dd").toNow(true);
    
    const age2 = moment.duration(moment().diff(moment(dateOfBirth)))._data["years"];
    
    console.log(age1);
    console.log(age2);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    【讨论】:

    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 2020-05-26
    • 2016-05-07
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多