You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中new Date构造函数的月份为何会自动加1?

问题解答

这是JavaScript Date对象的预期行为。

JavaScript的Date构造函数中,月份参数采用0基索引:

  • 0 对应 1月
  • 1 对应 2月
  • ...
  • 11 对应 12月

你代码里的new Date(2023,3,8),其中的3就对应4月,所以最终输出Sat Apr 08 2023是符合设计逻辑的;当你把月份改为0时,自然会显示1月。

如果想直接使用日常的1-12月份值来创建日期,可以用两种方式:

  • 手动将月份值减1:new Date(2023, 4-1, 8)(对应2023年4月8日)
  • 使用ISO格式的日期字符串:new Date('2023-04-08')(此时月份为1-12)

你的原始代码修正后如下:

function ExpenseItem() {
    const expenseDate = new Date(2023,3,8);
    const expenseTitle = 'Test';
    const expenseAmount = 200.00;

    return (
        <div className="expense-item">
            <div>{expenseDate.toDateString()}</div>
            <div className="expense-item__description">
                <h2>{expenseTitle}</h2>
                <div className="expense-item__price">£{expenseAmount}</div>
            </div>
        </div>)
}

内容的提问来源于stack exchange,提问作者shudson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:47:22