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

为什么JavaScript调用getDay()获取日期时返回值与预期不符?

原因说明

这是Date对象两个不同方法的功能差异导致的:

  • getDay() 返回的是星期几的序号,取值范围是0(周日)到6(周六)。你测试的日期2021年11月18日正好是周四,所以返回4,属于方法的正常返回结果。
  • 如果你需要获取当月的日期(也就是你预期的18),要使用getDate()方法,该方法返回1~31的整数,对应当前是当月的第几天。

调整后的代码

const currentDate = new Date();
console.log(currentDate); // 输出 "2021-11-18T07:29:05.205Z"
const dayOfWeek = currentDate.getDay();
console.log(dayOfWeek); // 输出 4,代表周四
const dayOfMonth = currentDate.getDate();
console.log(dayOfMonth); // 输出 18,符合你的预期

补充记忆点

两个方法的命名对应不同的时间维度:

  • getDay() 对应「星期几(Day of the week)」
  • getDate() 对应「当月日期(Date of the month)」

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:15:04