2
var now = new Date();
var dateString = now.getMonth() + "-" + now.getDate() + "-" + now.getFullYear() + " "
+ now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();

这里月份显示不正确。

例如,如果输出是 12 月,它会打印 11 月

now.getMonth() +1将显示正确的月份。

我正在寻找更好的方法。

我的应用程序必须在两个单选按钮之间进行选择。第一个选项应返回当前系统日期和时间,其他返回从 jsp 中选择的日期和时间。在选择这两个选项中的任何一个时,它应该以特定格式将日期返回给控制器。

4

3 回答 3

4

getMonth()根据定义返回从 0 到 11 的月份。

如果你不习惯这个,你可以改变一个Date对象的原型:

Date.prototype.getFixedMonth = function(){
    return this.getMonth() + 1;
}

new Date().getFixedMonth(); //returns 12 (December)
new Date("January 1 2012").getFixedMonth //returns 1 (January)

但这根本不推荐。


另一种方法

如果你愿意,你也可以这样做:

Date.prototype._getMonth = Date.prototype.getMonth;
Date.prototype.getMonth = function(){       //override the original function
    return this._getMonth() + 1;
}

new Date().getMonth(); //returns 12 (December)
new Date("January 1 2012").getMonth //returns 1 (January)
于 2012-12-31T07:35:20.873 回答
2

getMonth()应该将月份作为从 0 到 11 的索引返回(0 是一月,11 是十二月)。所以,你得到的是预期的返回值。

于 2012-12-31T07:31:48.643 回答
2

这是功能

 function GetTime_RightNow() {
        var currentTime = new Date()
        var month = currentTime.getMonth() + 1
        var day = currentTime.getDate()
        var year = currentTime.getFullYear()
        alert(month + "/" + day + "/" + year)
    }
于 2012-12-31T07:52:22.427 回答