javascript - 为什么我的 js 日期在 11 月份左右开始计算错误?

标签 javascript datetime

当我尝试添加接近 11 月 30 日(任何年份)的日期时,我的代码表现得很有趣:

Date.prototype.addDays = function(days){
    this.setDate(this.getDate() + days);
    return this;
};

function calculateDate(string_date, days_to_add){
    var arr, dat;

    arr = string_date.split(" ");
    dat = new Date(2013, (("enefebmarabrmayjunjulagosepoctnovdic".indexOf(arr[1])+3)/3), (((arr[0].charAt(0)!="0")?arr[0]:arr[0].substring(1))*1));
    dat.addDays(days_to_add*1);

    return (dat.getDate() + "/" + dat.getMonth() + "/"+dat.getFullYear());
}

现在如果我使用:

  • calculateDate("07 nov",24); 返回 31/11/2013(我的日历显示 2013 年 11 月的日期为 30)
  • calculateDate("07 nov",25); 返回 1/0/2014

我的代码似乎适用于任何其他月份和日期,那么为什么我的代码在 11 月至 12 月附近无法正常工作?计算机是否已经产生了感情并需要休假才能继续工作?

最佳答案

Date 对象 getMonth是一个从零开始的索引:

注意到“11 月”有 31 天吗?

关于javascript - 为什么我的 js 日期在 11 月份左右开始计算错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17560364/

相关文章:

javascript - 有人可以帮我解决按钮功能吗?

javascript - 为什么在 node.js v4.0.0 中弃用了许多 util.is* 函数?

datetime - formatDate() 给出正确的日期 -1 天(Google Apps 脚本)

MySQL错误: Could not execute MySQL-statement: Incorrect datetime value?

sql-server-2005 - SSIS 中的 Oracle 到 SQL 2005 DATETIME 字段溢出

c# - protobuf-net 编码 DateTime UTC 解码 ToLocalTime

javascript - 按提供的输入过滤值

javascript - 我应该在 bottom body 标签之前的脚本上使用 defer 吗?

javascript - 调用参数列表的函数

python - 如何在 pandas 中存储仅时间时间戳?