js格式化时间(指定模板格式)

 1 /** 格式化时间
 2  *  @param {string} date 需要格式化的时间
 3  *  @param {string} fmt 想要格式化的格式
 4  */
 5 function formatDate(date, fmt) {
 6   if (/(y+)/.test(fmt)) {
 7     fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
 8   }
 9   let o = {
10     'M+': date.getMonth() + 1,
11     'd+': date.getDate(),
12     'h+': date.getHours(),
13     'm+': date.getMinutes(),
14     's+': date.getSeconds()
15   };
16   for (let k in o) {
17     if (new RegExp(`(${k})`).test(fmt)) {
18       let str = o[k] + '';
19       fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
20     }
21   }
22   return fmt;
23 };
24 
25 function padLeftZero(str) {
26   return ('00' + str).substr(str.length);
27 };
28 
29 <script>
30     let date = new Date();
31     let res = formatDate(date,'yyyy++MM++dd hh:mm:ss') // 传入想要的格式即可
32     let res1 = formatDate(date,'yyyy++MM++dd')
33     console.log('formatDate res ==> ', res);
34     console.log('formatDate res1 ==> ', res1);
35 </script>

 

posted @ 2021-04-09 10:40  Amerys  阅读(499)  评论(0编辑  收藏  举报