Web Analytics Made Easy -
StatCounter prototype Date conversions & single digit padleft - CodingForum

Announcement

Collapse
No announcement yet.

prototype Date conversions & single digit padleft

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • prototype Date conversions & single digit padleft

    I have noticed a number of forum members wanting to change the date format.
    Here is a small prototype function to form date into YYYYMMDD and DDMMYYYY formats.
    Function includes an optional separator character for the display.
    Others can be created with a bit of re-arrangement.

    Also added a function to add or subtract a number of days from the chosen date.

    Also includes a number padding function so that numbers less than 10 are padded with one '0' to the left of the number.
    This could be an optional or stand alone function.

    Code:
    <script type="text/javascript">
    Number.prototype.padDigit = function() {
      var n = this;  
      return n = (n < 10) ? '0'+n : n; 
    }
    Date.prototype.toYYYYMMDD = function(sep) {
      var y = this.getFullYear();
      var m = this.getMonth()+1;
      var d = this.getDate();
      return ''+y+sep+m.padDigit()+sep+d.padDigit();
    }
    Date.prototype.toDDMMYYYY = function(sep) {
      var y = this.getFullYear();
      var m = this.getMonth()+1;
      var d = this.getDate();
      return ''+d.padDigit()+sep+m.padDigit()+sep+y;
    }
    Date.prototype.addDays = function (days) {
      return new Date(this.getTime() + days*24*60*60*1000);
    }
    
    // testing code
    var str = '';
        str = new Date().toYYYYMMDD('');  // Current date and Aug. 1, 2011
        str += '\n'+new Date(2011,7,1).toYYYYMMDD('/');
        str += '\n\n';
        str += new Date().toDDMMYYYY('-');  // Current date and Aug. 3, 2012
        str += '\n'+new Date(2012,7,3).toDDMMYYYY('');
        str += '\n\n';
        str += new Date().toDDMMYYYY('_');  // Current date and Aug. 16, 2012
        str += '\n'+new Date(2012,7,16).toYYYYMMDD('.');
        str += '\n\n';
        str += new Date('Aug 16, 2011').toYYYYMMDD('.');  // Aug. 16, 2011 and Aug. 3, 2012
        str += '\n'+new Date('Aug 3, 2012').toYYYYMMDD('/');
        str += '\n\n';
    var today = new Date();
        str += today.toYYYYMMDD('');              // Current date
        str += '\n';
        str += today.addDays(14).toYYYYMMDD('');  // plus 2 weeks
        str += '\n';
        str += today.addDays(-14).toYYYYMMDD('');  // minus 2 weeks
    alert(str);
    </script>
    Last edited by jmrker; Aug 18, 2011, 11:37 PM. Reason: Added a function.
Working...
X
😀
🥰
🤢
😎
😡
👍
👎