日期为2013年4月1日而非2013年3月31日

时间:2013-03-12 21:15:20

标签: javascript date

我有这两个函数以正确的格式创建一个新字符串(mm-dd-yyyy)但是现在它似乎运行得不好......当我输入日期31-03-2013时有效日期,它出现在04-01-2013之后,就像在......之后的第一个月......

以下是两个功能:

Date.prototype.sqlDate = Date.prototype.sqlDate || function () {
    return this.getMonth() + "-" + this.getDate() + "-" + this.getFullYear();
};

String.prototype.sqlDate = String.prototype.sqlDate || function () {
    var date = new Date(0);
    var s = this.split("-");
    //If i log "s" here its output is: 
    //    ["31", "03", "2013", max: function, min: function]
    date.setDate(s[0]);
    date.setMonth(s[1]);
    date.setYear(s[2]);
    return date.sqlDate();
};

2 个答案:

答案 0 :(得分:8)

月份日期是0月1日至12月11日之间的数字,

所以3月是4月......

这非常烦人,因为:

  • - 1到31.一个基础索引
  • - 0到11.零基础索引。

嗯... javascript的规格......继续。

MDN

您可以使用它来设置正确:

date.setMonth(parseInt(s[1], 10) - 1);

你可以在这里看到它的作用:

example

答案 1 :(得分:3)

试试这个:

String.prototype.sqlDate = String.prototype.sqlDate || function () {
    var date = new Date(0);
    var s = this.split("-");
    //If i log "s" here its output is: 
    //    ["31", "03", "2013", max: function, min: function]
    date.setDate(s[0]);
    date.setMonth(parseInt(s[1],10)-1);
    date.setYear(s[2]);
    return date.sqlDate();
};
相关问题