.getMonth()
返回的是从0开始计数的数字,因此为了获得正确的月份,需要加1。例如,在五月调用.getMonth()
会返回4
而不是5
。
因此,在你的代码中,我们可以使用currentdate.getMonth()+1
来输出正确的值。此外:
.getDate()
返回月份中的某一天<- 这才是你想要的
.getDay()
是Date
对象的另一个方法,它将返回表示当前星期几的整数(0-6),其中0 == 星期日
等等
因此,你的代码应该像这样:
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。您可以修改构造函数的prototype对象以影响JavaScript Date实例继承的属性和方法。
您可以利用Date原型对象创建一个新方法,该方法将返回今天的日期和时间。这些新方法或属性将被所有Date对象的实例继承,因此如果需要重复使用此功能,则特别有用。
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
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();