js 格式化时间戳

js格式化时间戳,根据传入时间格式返回相应格式的时间

 1 function (date = 0, fmt = 'yyyy-MM-dd hh:mm:ss') {
 2     
 3     date = new Date(+date)
 4     if (/(y+)/.test(fmt)) {
 5       fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
 6     }
 7     let o = {
 8       'M+': date.getMonth() + 1,
 9       'd+': date.getDate(),
10       'h+': date.getHours(),
11       'm+': date.getMinutes(),
12       's+': date.getSeconds()
13     };
14     for (let k in o) {
15       if (new RegExp(`(${k})`).test(fmt)) {
16         let str = o[k] + '';
17         fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
18       }
19     }
20     return fmt;
21   }

以上

猜你喜欢

转载自www.cnblogs.com/blackbentel/p/11769737.html
今日推荐