Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
  1. #1
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,086
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Lightbulb 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; 08-19-2011 at 04:37 AM. Reason: Added a function.


 

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •