Format Date as yyyy_mm_dd, yyyy_mm_ddTHH_mm_ss, yyyy_mm_ddTHH_mm - Node.js Date

Node.js examples for Date:Date Format

Description

Format Date as yyyy_mm_dd, yyyy_mm_ddTHH_mm_ss, yyyy_mm_ddTHH_mm

Demo Code


Date.prototype.toLogDay= function() {  //yyyy_mm_dd

  return this.getFullYear() + '_'
  + mk2digit( this.getMonth() + 1) + '_' 
  + mk2digit( this.getDate() );/*from   w  w  w.j a v  a2s  .c  om*/
}

Date.prototype.toLogTime= function() {  //yyyy_mm_dd

  return mk2digit( this.getHours() ) + '_'
  + mk2digit( this.getMinutes() ) + '_'
  + mk2digit( this.getSeconds() );
}

Date.prototype.toLogDate= function() {  //yyyy_mm_ddTHH_mm_ss

  return this.getFullYear() + '_'
  + mk2digit( this.getMonth() + 1) + '_' 
  + mk2digit( this.getDate() ) + 'T' 
  + mk2digit( this.getHours() ) + '_'
  + mk2digit( this.getMinutes() ) + '_'
  + mk2digit( this.getSeconds() );
}

Date.prototype.printDate= function(date) {  //yyyy_mm_ddTHH_mm

  var dateStr = mk2digit(date.getFullYear()) + '_'
                  + mk2digit(1 + date.getMonth()) + '_'
                  + mk2digit(date.getDate()) + 'T'
                  + mk2digit(date.getHours()) + '_'
                  + mk2digit(date.getMinutes()); 
          // + '_'
          // + mk2digit(date.getSeconds());
          
  return dateStr;  
}

date.diffTime = function(startDate, endDate) {  //HH_mm_ss

  var dist  = endDate.getTime() - startDate.getTime();
  var HH = (1000 * 60 * 60);
  var MM = (1000 * 60);
  var SS = (1000);
  
  var hh = Math.floor( dist / HH);
  var mm = Math.floor( (dist % HH) / MM );
  var ss = Math.floor( ((dist % HH) % MM) / SS );

  var strTime = mk2digit(hh) + ":" + mk2digit(mm) + ":" + mk2digit(ss);
  
  return mk2digit(hh) + ":" + mk2digit(mm) + ":" + mk2digit(ss);
}

date.toLogDate = function(date) {
  return (new Date()).toLogDate();
}

date.distance = function(date) {
  return (new Date()).diffTime(date);
}

mk2digit = function(i) {
    return (i < 10) ? "0" + i : "" + i;
}

Related Tutorials