小编典典

在JavaScript中获取当前日期和时间

javascript

我有一个可在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

有什么帮助吗?谢谢


阅读 666

收藏
2020-05-01

共1个答案

小编典典

.getMonth()返回一个从零开始的数字,以便获得正确的月份,您需要将其加1,因此调用.getMonth()in可能会返回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();
2020-05-01