题解 | #时间格式化输出#
https://www.nowcoder.com/practice/a789783e7c984f10a0bf649f6d4e2d59
function add(str,data){ if(str.length == 2 && data<10){ return "0"+data; } return data; } function formatDate(date,str){ // 深复制,存储匹配到的需要替换的字符串 let newArr = str.match(/\w+/g); let arr = []; for(let k in newArr){ arr[k] = newArr[k]; } // 星期数 let day=["日","一","二","三","四","五","六"] // 按照题目要求得到对应时间数据 for(let i in newArr){ switch(newArr[i][0]){ case "y": if(newArr[i].length == 4){ newArr[i] = date.getFullYear(); }else{ newArr[i] = date.getYear()-100; } break; case "M": newArr[i] = add(newArr[i],date.getMonth()+1); break; case "d": newArr[i] = add(newArr[i],date.getDate()); break; case "H": newArr[i] = add(newArr[i],date.getHours()); break; case "h": newArr[i] = add(newArr[i],date.getHours()%12); break; case "m": newArr[i] = add(newArr[i],date.getMinutes()); break; case "s": newArr[i] = add(newArr[i],date.getSeconds()); break; case "w": newArr[i] = day[date.getDay()]; break; } } // 字符串匹配和替换 for(let k in arr){ str = str.replace(arr[k],newArr[k]); } // 返回替换后的字符 return str }