Implement a date formatting tool using pure javascript

requirements description
// 
let date = new Date() // "Tue Jul 17 2018 21:22:16 GMT+0800 ()"
let dateStr = new Date().getTime() // 1531833769882
// 
let time1 = dateFormat(date, "yyyy-mm-dd HH:MM:ss") // 2018-7-17 21:22:16
let time2 = dateFormat(date, "yyyy-mm-dd HH:MM:ss") // 2018-7-17 21:22:16
how to implement the function dateFormat
Mar.28,2021

clipboard.png


function dateFormater(formater,t){
    var date = t ? new Date(t) : new Date(),
        Y = date.getFullYear() + '',
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    return formater.replace(/YYYY|yyyy/g,Y)
        .replace(/YY|yy/g,Y.substr(2,2))
        .replace(/MM/g,(M<10?'0':'') + M)
        .replace(/DD/g,(D<10?'0':'') + D)
        .replace(/HH|hh/g,(H<10?'0':'') + H)
        .replace(/mm/g,(m<10?'0':'') + m)
        .replace(/ss/g,(s<10?'0':'') + s)
}

//  Date Date String (M)(d)(h)(m)(s)(q)  1-2
//  (y) 1-4 (S) 1 ( 1-3 ) :
// (new Date()).formate("yyyy-MM-dd")            ==>  2018-07-18
// (new Date()).formate("yyyy-MM-dd hh:mm:ss")   ==>  2018-07-18 10:01:49
// (new Date()).formate("yyyy-MM-dd hh:mm:ss.S") ==>  2018-07-18 10:10:01.956
// (new Date()).formate("yyyy-M-d h:m:s.S")      ==>  2018-7-18 10:11:9.724
Date.prototype.formate = function (format) {
  const o = {
    "M+": this.getMonth() + 1, // month
    "d+": this.getDate(), // day
    "h+": this.getHours(), // hour
    "m+": this.getMinutes(), // minute
    "s+": this.getSeconds(), // second
    "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
    S: this.getMilliseconds()
    // millisecond
  };

  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      `${this.getFullYear()}`.substr(4 - RegExp.$1.length)
    );
  }

  for (const k in o) {
    if (new RegExp(`(${k})`).test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
      );
    }
  }
  return format;
};

 let date = new Date();
    console.log(date.formate("yyyy-MM-dd")) 
    console.log(date.formate("yyyy-MM-dd hh:mm:ss")) 
    console.log(date.formate("yyyy-MM-dd hh:mm:ss.S")) 
    console.log(date.formate("yyyy-M-d h:m:s.S"))
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3b2e9-4eed9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3b2e9-4eed9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?