获取时间
在js中,可以使用new Date( )来获取当前的时间
let time = new Date() console.log(time) //打印结果为:Wed Aug 31 2022 10:47:48 GMT+0800 (中国标准时间) console.log(time.toLocaleString()) //打印结果为:2022/8/31 10:49:41 console.log(time.toLocaleDateString()) //打印结果为:2022/8/31 console.log(time.toDateString()) //打印结果为:Wed Aug 31 2022 console.log(time.toLocaleTimeString()) //打印结果为:10:53:04 console.log(time.toTimeString()) //打印结果为:10:54:25 GMT+0800 (中国标准时间)
日期格式化
如果有一个需求,需要将当前日期格式化为yyyy-MM-dd hh:mm:ss
function timestampToTime(times) { let time = times[1] let mdy = times[0] mdy = mdy.split('/') let month = parseInt(mdy[0]); let day = parseInt(mdy[1]); let year = parseInt(mdy[2]) return year + '-' + month + '-' + day + ' ' + time } let time = new Date() let nowTime = timestampToTime(time.toLocaleString('en-US',{hour12: false}).split(" ")) console.log(nowTime) //打印结果为:2022-8-31 11:08:34