Javascript Date format(pattern)

Description

Javascript Date format(pattern)


//Prototype/* www  .j  a v  a 2  s  .com*/
Date.prototype.format = function (pattern) {
    return moment(this).format(pattern);
}

Javascript Date format(pattern)

Date.prototype.format = function(pattern) {
 var returnValue = pattern;
 var format = {/*w  ww  .  jav a 2s . c o m*/
  "y+": this.getFullYear(),
  "M+": this.getMonth() + 1,
  "d+": this.getDate(),
  "H+": this.getHours(),
  "m+": this.getMinutes(),
  "s+": this.getSeconds(),
  "S": this.getMilliseconds(),
  "h+": (this.getHours() % 12),
  "a": (this.getHours() / 12) <= 1 ? "AM" : "PM"
 };
 for(var key in format) {
  var regExp = new RegExp("(" + key + ")");
  if(regExp.test(returnValue)) {
   var zero = "";
   for(var i = 0; i < RegExp.$1.length; i++) {
    zero += "0";
   }
   var replacement = RegExp.$1.length == 1 ? format[key] : (zero + format[key]).substring((("" + format[key]).length));
   returnValue = returnValue.replace(RegExp.$1, replacement);
  }
 }
 return returnValue;
};



PreviousNext

Related