栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517983.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号