JS( 四 )


4.2_时间格式化
// yyyy/MM/dd hh:mm:ss// yyyy*MM*dd hh-mm-ss// dayjs/momentfunction formatTime(timestamp, fmtString) {// 1.将时间戳转成Dateconst date = new Date(timestamp)// // 2.获取到值// const year = date.getFullYear()// const month = date.getMonth() + 1// const day = date.getDate()// const hour = date.getHours()// const minute = date.getMinutes()// const second = date.getSeconds()// // 3.创建正则// const yearRe = /y+/// const monthRe = /M+/// 2.正则和值匹配起来const dateO = {"y+": date.getFullYear(),"M+": date.getMonth() + 1,"d+": date.getDate(),"h+": date.getHours(),"m+": date.getMinutes(),"s+": date.getSeconds()}// 3.for循环进行替换for (const key in dateO) {const keyRe = new RegExp(key)if (keyRe.test(fmtString)) {const value = http://www.kingceram.com/post/(dateO[key] +"").padStart(2, "0")fmtString = fmtString.replace(keyRe, value)}}return fmtString}// 某一个商品上架时间, 活动的结束时间const timeEl = document.querySelector(".time")const productJSON = {name: "iPhone",newPrice: 4999,oldPrice: 5999,endTime: 1099292301637}timeEl.textContent = formatTime(productJSON.endTime, "hh:mm:ss yyyy-MM-dd")//14:58:21 2004-11-01