How to encapsulate a time formatting function in native js

In the project, we often encounter some requirements on how to convert the time format into a format that you want. Of course, you can use some third-party plug-ins such as moment. This is already packaged by others. If you want to become a A thinking programmer, not a porter, you have to understand how native js encapsulates a time formatting function by itself. The code is as follows:


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

Guess you like

Origin blog.csdn.net/qq_42671194/article/details/108669337