【问题标题】:Formatting date method returns wrong month [duplicate]格式化日期方法返回错误的月份[重复]
【发布时间】:2019-07-24 11:28:45
【问题描述】:

我有将 startDate 和 endDate 格式化为“mm dd yyyy”格式的函数。

问题是每次这个函数返回低一个月:

const formatingDate = (dates) => {
  const d = new Date(dates);
  return `${d
    .getMonth()
    .toString()
    .padStart(2, '0')}/${d
    .getDate()
    .toString()
    .padStart(2, '0')}/${d.getFullYear()}`;
};

这是方法formattingDate()的参数

[2019 年 7 月 3 日星期三 00:00:00 GMT+0200(中欧夏令时间),
2019 年 8 月 1 日星期四 23:59:59 GMT+0200(中欧夏令时间)]

如何修复这个formattingDate() 函数以返回正确的月份?

【问题讨论】:

  • 月份从零开始。

标签: javascript reactjs


【解决方案1】:

请参考本文档

getMonth

月份是从 0 到 n-1

【讨论】:

    【解决方案2】:

    JS 月份范围为 0-11。所以你必须给月加 1。

    const formatingDate = (dates) => {
        const d = new Date(dates);
        return `${(d.getMonth() + 1)
            .toString()
            .padStart(2, '0')}/${d
            .getDate()
            .toString()
            .padStart(2, '0')}/${d.getFullYear()}`;
    };
    
    console.log(formatingDate('2019-07-24'))

    Reference.

    【讨论】:

    • 没有帮助...谢谢
    • 如果我这个d.getMonth() + (1).toString() 作为结果得到这个日期:prnt.sc/ojdfsz
    • 是的,我注意到了,更新了答案。
    • 另外,请投票关闭,因为这有很多重复。
    猜你喜欢
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多