- 最常用的方法
let date = new Date(times); let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDate(); let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds(); month = month > 10 ? month : "0" + month; day = day > 10 ? day : "0" + day; hour = hour > 10 ? hour : "0" + hour; minute = minute > 10 ? minute : "0" + minute; second = second > 10 ? second : "0" + second; return `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
- ES6语法中使用padstart添加
// padStart() 用于头部补全,padEnd() 用于尾部补全 let s = 3 let str1 = String(s).padStart(2, '0') //03 let str2 = String(m).padStart(2, '0') //03
- String.protorype.slice(),参数为开始截取的位置。为负数的话就从后边往前面数,-1就是最后一个,-2就永远只截取最后两个
let a = 9 let newA = ("012340" + a).slice(-2) // 打印 09
日期格式化,不足两位数补0
最新推荐文章于 2024-04-19 14:02:09 发布