鍍金池/ 問答/C  HTML/ 使用純 javascript 實現(xiàn)一個日期格式化工具

使用純 javascript 實現(xiàn)一個日期格式化工具

需求描述
// 獲取時間戳
let date = new Date() // "Tue Jul 17 2018 21:22:16 GMT+0800 (中國標(biāo)準(zhǔn)時間)"
let dateStr = new Date().getTime() // 1531833769882
// 格式化結(jié)果
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
如何實現(xiàn)函數(shù) dateFormat
回答
編輯回答
熊出沒

clipboard.png

2017年6月9日 15:31
編輯回答
巫婆
// 獲取當(dāng)前日期 對Date的擴(kuò)展,將 Date 轉(zhuǎn)化為指定格式的String 月(M)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2
// 個占位符, 年(y)可以用 1-4 個占位符,毫秒(S)只能用 1 個占位符(是 1-3 位的數(shù)字) 例子:
// (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"))
2017年11月14日 04:45
編輯回答
浪蕩不羈
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)
}
2017年2月13日 15:56