我有一个用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:333/3/2012 15:07:33

推荐答案

.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();

Javascript相关问答推荐

jsfat的黑色画布输出

如何使图像逐渐/平稳地响应(先减少宽度,然后减少高度)

React中的表格中 Select Radio按钮

在JavaScript中,如何将请求的回调函数的结果合并到运行的代码中?

创建私有JS出口

创建1:1比例元素,以另一个元素为中心

如何按预期聚合SON数据?

为什么从liveWire info js代码传递数组我出现错误?

网页自检测外部元素无法加载

有没有可能使滑动img动画以更快的速度连续?

将本机导航路由react 到导航栏中未列出的屏幕?

如何让npx在windows中运行js脚本?

html + java script!需要帮助来了解为什么我得到(无效的用户名或密码)

变量的值在Reaction组件中的Try-Catch语句之外丢失

使用Java脚本导入gltf场景并创建边界框

如何迭代叔父元素的子HTML元素

检索相加到点的子项

如何在Press上重新启动EXPO-AV视频?

在验证和提交表单后使用useNavigate()进行react 重定向,使用带有加载器和操作的路由

基于产品ID更新条带产品图像的JavaScript命中错误