You need to enable JavaScript to run this app. Date()对象打印日期正常但调用getMonth、getDay等方法返回值错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Date()对象打印日期正常但调用getMonth、getDay等方法返回值错误如何解决

问题根源

你遇到的情况是JavaScript Date对象的API设计特性导致的,不属于对象本身的bug,两个核心错误点:

  • getMonth()的返回值为0基索引,取值范围是0(对应1月)`11`(对应12月),你示例中的日期是7月,返回`6`是完全符合API规则的,只需要手动+1就能得到常规的112的月份数值。
  • getDay()的返回值是星期序号,取值范围是0(对应周日)`6`(对应周六),你需要获取月份中的日期,应该调用`getDate()`方法,它会返回131的月内天数。
  • 补充:JavaScript标准Date对象不存在getFullMonth()方法,调用这个不存在的方法当然无法得到正确结果。

为什么直接打印Date对象是正常的

Date对象的toString()/toUTCString()方法内部已经自动处理了0基月份的转换,也会直接输出月内的日期数值,所以你直接打印对象时看到的结果符合日常阅读习惯,和调用方法返回的结果差异是API设计导致的,不是对象本身数据错误。

修正方案

把你代码中获取月、日的部分做如下修改即可:

// 原错误代码
// let month = String(currentDateObj.getMonth());
// let day = String(currentDateObj.getDay());

// 修正为本地时间版本
let month = String(currentDateObj.getMonth() + 1);
let day = String(currentDateObj.getDate());

// 如果需要和打印的UTC时间对齐,避免时区差异,用UTC对应方法
// const year = String(currentDateObj.getUTCFullYear());
// let month = String(currentDateObj.getUTCMonth() + 1);
// let day = String(currentDateObj.getUTCDate());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 05:36:03