.getMonth()
返回一个从零开始的数字,因此要获得正确的月份,您需要添加1,因此在5月份呼叫.getMonth()
将返回4
,而不是5
.
因此,在您的代码中,我们可以使用currentdate.getMonth()+1
来输出正确的值.此外,还包括:
.getDate()
返回该月的第<- this is the one you want天
.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日期实例继承自日期.原型可以修改构造函数的原型对象,以影响JavaScript日期实例继承的属性和方法
您可以使用Date
prototype对象创建一个新方法,该方法将返回今天的日期和时间.这些新方法或属性将由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();