Javascript Date format(str)

Description

Javascript Date format(str)



Date.prototype.format = function (str) {
  const o = {/*from   w w w.  j a v  a2s.  com*/
    'y+': this.getFullYear(),
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds()
  }

  Object.keys(o).forEach(element => {
    str = str.replace(new RegExp(element), substr => {
      return String.prototype.padStart.call(o[element], substr.length, '0')
    })
  })
  return str
}



PreviousNext

Related