美文网首页
JS Date 转时间字符串格式化

JS Date 转时间字符串格式化

作者: 夹板儿孩 | 来源:发表于2021-09-23 16:04 被阅读0次

javascript 时间转字符串并格式化为 yyyy-MM-dd hh:mm:ss

Date.prototype.format = function (format) {
  let o = {
    "y": "" + this.getFullYear(),
    "M": "" + (this.getMonth() + 1),  //month
    "d": "" + this.getDate(),         //day
    "h": "" + this.getHours(),        //hour
    "m": "" + this.getMinutes(),      //minute
    "s": "" + this.getSeconds(),      //second
    "S": "" + this.getMilliseconds(), //millisecond
  }
  return Object.keys(o).reduce((pre, k)=> (new RegExp("(" + k + "+)").test(pre)) ? (pre.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : o[k].padStart(2, "0"))) : pre , format);
}

//日期格式化
var d = new Date();
var useDate = d.format('yyyy-MM-dd');
var useDate2 = d.format('yyyy-MM-dd hh:mm:ss');

相关文章

网友评论

      本文标题:JS Date 转时间字符串格式化

      本文链接:https://www.haomeiwen.com/subject/rjdogltx.html