用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>`

执行结果:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。