js获取当前日期,格式 YYYY-MM-DD HH:mm:ss

用js获取当前时间,并转为YYYY-MM-DD HH:mm:ss

1、先实例化Date()

2、在获取年月日时分秒

        getFullYear(): 获取年份,四位数的年份

        getYear():获取年份,两位数的年份

        getMonth():获取月份,注:获取的值是0-11,所以获取后加1才是当前正确的月份

        getDate():获取当前日期

        getDay():获取当前星期几,注:获取值是0-6,0是周日,1-6分别是周一到周六

        getHours():获取小时数

        getMinutes():获取分钟数

        getSeconds():获取秒数

 const dateTime = new Date()
        function format(){
            const year = dateTime.getFullYear()
            const month = dateTime.getMonth() + 1 > 9 ? dateTime.getMonth() + 1 : '0' + dateTime.getMonth()
            const day = dateTime.getDate() > 9 ? dateTime.getDate() : '0' + dateTime.getDate()

            const hour = dateTime.getHours() > 9 ? dateTime.getHours() : '0' + dateTime.getHours()
            const minute = dateTime.getMinutes() > 9 ? dateTime.getMinutes() : '0' + dateTime.getMinutes()
            const second = dateTime.getSeconds() > 9 ? dateTime.getSeconds() : '0' + dateTime.getSeconds()

            return `${year}-${month}-${day} ${hour}:${minute}:${second}`
        }

        const current = format();
        document.querySelector('p').innerHTML = `当前时间:<strong>${current}</strong>`

执行结果:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值