原生js如何封装一个时间格式化函数

在项目中我们经常遇到一些需求就是如何把时间格式转成一个自己想要的格式,当然啦,你可以使用一些第三方插件比如moment,这是别人已经封装好的,如果你想成为一名有思想的程序员,而不是一位搬运工,你得明白原生js如何自己封装一个时间格式化函数,代码如下:


function formatDate(value, fmt) {
    
    
  let getDate = new Date(value);
  let o = {
    
    
    'M+': getDate.getMonth() + 1,
    'd+': getDate.getDate(),
    'h+': getDate.getHours(),
    'm+': getDate.getMinutes(),
    's+': getDate.getSeconds(),
    'q+': Math.floor((getDate.getMonth() + 3) / 3),
    'S': getDate.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    
    
    fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    
    
    if (new RegExp('(' + k + ')').test(fmt)) {
    
    
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    }
  }
  return fmt;
}
let d = new Date();
console.log(formatDate(d, 'yyyy-MM-dd')); // 2020-09-18
console.log(formatDate(d, 'yyyy:MM:dd')); // 2020:09:18
console.log(formatDate(d, 'yyyy-MM-dd hh:mm')); // 2020-09-18 17:26

猜你喜欢

转载自blog.csdn.net/qq_42671194/article/details/108669337