不足2位补'0':
也有个函数padStart(),padEnd() https://blog.csdn.net/ixygj197875/article/details/79090578
export function pad(num, n = 2) { let len = num.toString().length while (len < n) { num = '0' + num len++ } return num }
格式化秒数为: 05: 30的格式
export function formatTime(interval) { interval = interval | 0 const minute = pad((interval / 60) | 0) const second = pad(interval % 60) return `${minute}:${second}` }
格式化日期为任意格式:
export function formatDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') { date = date instanceof Date ? date : new Date(date) if (/(y+)/.test(fmt)) { fmt = fmt.replace( RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length) ) } let o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() } for (let k in o) { if (new RegExp(`(${k})`).test(fmt)) { let str = o[k] + '' fmt = fmt.replace( RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str) ) } } return fmt }