方法一:map()
function currentTime() {
let T = new Date();
let [y, M, d, h, m, s] = [T.getFullYear(), T.getMonth() + 1, T.getDate(), T.getHours(), T.getMinutes(), T.getSeconds()];
[y, M, d, h, m, s] = [y, M, d, h, m, s].map(n => n = n < 10 ? '0' + n : n); //ES6箭头函数,为小于10的数字前面加0
return y + '-' + M + '-' + d + ' ' + h + ':' + m + ':' + s;
}
console.log(currentTime()) //2021-09-01 09:52:55
方法二:padStart()
padStart() 方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。
str.padStart(targetLength,string):
使用指定字符串填充到目标字符串前面,使其达到目标长度;
str.padEnd(targetLength,string):
使用指定字符串填充到目标字符串后面,使其达到目标长度;
function formatDayTime() {
const date = new Date()
return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
}
console.log(formatDayTime()) //2021-09-01 09:52:55