发布于 4年前

JS 如何日期格式化获

 Date.prototype.format = function(format) {
  var args = {
    'M+': this.getMonth() + 1,
    'D+': this.getDate(),
    'H+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3), //quarter
    S: this.getMilliseconds()
  }
  if (/(Y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var i in args) {
    var n = args[i]
    if (new RegExp('(' + i + ')').test(format))
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ('00' + n).substr(('' + n).length))
  }
  return format
}

// 使用方式
// 日期和时间
new Date().format("YYYY-MM-DD HH:mm")      // 2019-03-10 12:03
new Date().format("YYYY-M-D H:m")    // 2019-3-10 12:3
// 日期
new Date().format("YYYY-MM-DD")    // 2019-03-10
new Date().format("YYYY-M-D")    // 2019-3-10
©2020 edoou.com   京ICP备16001874号-3