JavaScript で現在の日付と時刻を出力するスクリプトがあるのですが、DATE
常に間違っています。コードは次のとおりです。
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
18/04/2012 15:07:33
印刷されるはずです3/3/2012 15:07:33
ベストアンサー1
.getMonth()
は 0 から始まる数値を返すため、正しい月を取得するには 1 を加算する必要があります。したがって、 may を呼び出すと ではなく が.getMonth()
返されます。4
5
したがって、コードではcurrentdate.getMonth()+1
正しい値を出力するために使用できます。さらに:
.getDate()
月の日付を返します<- これがあなたが求めているものです.getDay()
オブジェクトの別のメソッドでありDate
、現在の曜日(0-6)0 == Sunday
などを表す整数を返します。
コードは次のようになります。
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
JavaScript DateインスタンスはDate.prototypeを継承します。コンストラクタのプロトタイプオブジェクトを変更して、JavaScript Dateインスタンスが継承するプロパティとメソッドに影響を与えることができます。
プロトタイプ オブジェクトを使用してDate
、今日の日付と時刻を返す新しいメソッドを作成できます。これらの新しいメソッドまたはプロパティは、オブジェクトのすべてのインスタンスに継承されるDate
ため、この機能を再利用する必要がある場合に特に便利です。
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
次の手順を実行するだけで、日付と時刻を簡単に取得できます。
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();
または、メソッドをインラインで呼び出すと、単純に次のようになります。
var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();