Date Formatter - Node.js Date

Node.js examples for Date:Date Format

Description

Date Formatter

Demo Code


Date.formators = {/*  ww w. ja  v  a  2 s.c  om*/
  
  y: function (date, length){
    date = date.getFullYear();
    return length < 3 && date < 2000 ? date % 100 : date;
  },
  
  M: function(date){
    return date.getMonth() + 1;
  },
  
  d: function(date){
    return date.getDate();
  },
  
  H: function(date){
    return date.getHours();
  },
  
  m: function(date){
    return date.getMinutes();
  },
  
  s: function(date){
    return date.getSeconds();
  },
  
  e: function(date, length){
      return (length === 1 ? '' : length === 2 ? '?' : '??') + [length === 2 ? '?' : '?', '?', '?', '?', '?', '?', '?'][date.getDay()];
  }
  
};

Date.prototype.format = function (format) {
  var me = this;
    return (format || 'yyyy/MM/dd HH:mm:ss').replace(/(\w)\1*/g, function (all, key) {
    if(key in Date.formators){
      key = '' + Date.formators[key](me, all.length);
      while(key.length < all.length){
        key = '0' + key;
      }
      all = key;
    }
        return all;
    });
};

Date.prototype.addDay = function (value) {
    return new Date(+this + value * 86400000);
};

Date.prototype.addMonth = function (value) {
  var date = new Date(+this);
    date.setMonth(date.getMonth() + value);
  if(this.getDate() !== date.getDate()) { 
    date.setDate(0);
  }
    return date;
};

Date.prototype.clearHours = function (){
  this.setMilliseconds(0);
  this.setSeconds(0);
  this.setMinutes(0);
  this.setHours(0);
  return this;
};

Related Tutorials