3

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();
};
4

2 回答 2

8

Month of Date 是介于 0-Jan 和 11-Dec 之间的数字,

所以3是4月...

这非常烦人,因为:

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

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

MDN

您可以使用它来设置它:

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

你可以在这里看到它的工作原理:

例子

于 2013-03-12T21:17:32.623 回答
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();
};
于 2013-03-12T21:20:20.137 回答