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

ここで月が正しく表示されません。

出力が 12 月の場合、11 月と出力される例

now.getMonth() +1正しい月が表示されます。

より良いアプローチを探しています。

私のアプリケーションは、2 つのラジオボタンから選択する必要があります。最初のオプションは現在のシステムの日付と時刻を返し、他のオプションは jsp から選択された日付と時刻を返す必要があります。2 つのオプションのいずれかを選択すると、特定の形式で日付がコントローラーに返されます。

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

ここに関数があります

 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 に答える
2

getMonth()月を 0 から 11 までのインデックスとして返すことになっています (0 は 1 月、11 は 12 月)。したがって、得られるのは期待される戻り値です。

于 2012-12-31T07:31:48.643 に答える