1

I've an input that is filled by jQuery/JS. Currently it fills the input with a date value like this 2017-3-7 but I want it to be 2017-03-07.

I've a jsfiddle here: https://jsfiddle.net/ua8rngzw/

And the code is as follows:

(function ($) {
  $(document).ready(function() {
    var now = new Date();
    var created = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
    $('#created').val(created);
  });
})(jQuery);    

What is the easiest and quickest way to do such a thing?

Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
purple11111
  • 653
  • 5
  • 18
  • Possible duplicate of [How to format a JavaScript date](http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – bejado Mar 07 '17 at 20:26

3 Answers3

7

We can create a simple function that takes in a value and based on its length, pre-pends a zero to it. Then, take your date portions and run them through the function:

(function ($) {    
  $(document).ready(function() {
    var now = new Date();
    var created = now.getFullYear() + '-' + 
                  fixDigit(now.getMonth() + 1) + 
                  '-' + fixDigit(now.getDate());
    $('#created').val(created);
  });
      
  // Utility function to prepend zeros to single digits:
  function fixDigit(val){
    return val.toString().length === 1 ? "0" + val : val;
  }
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="created">
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
  • 1
    The body of *fixDigit* would be simpler as `return (val < 10? '0' : '') + val;`. ;-) – RobG Mar 07 '17 at 22:27
1
(function ($) {
  $(document).ready(function() {
    var now = new Date();
    mo = now.getMonth() + 1;
    if (mo < 10) {
        mo = "0" + mo;
    }
    date = now.getDate();
    if (date < 10) {
            date = "0" + date;
        }

        var created = now.getFullYear() + '-' + mo + '-' + date;
    $('#created').val(created);
  });
})(jQuery);    
Neil
  • 13,042
  • 2
  • 26
  • 48
0

The possible solution is:

(function ($) {    
      $(document).ready(function() {
     var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth()+1; //January is 0!
            var yyyy = today.getFullYear();

            if(dd<10) {
                dd='0'+dd
            } 

            if(mm<10) {
                mm='0'+mm
            } 

            var created = yyyy+'-'+mm+'-'+gg;
document.write(created);
    })(jQuery); 
FabioBranch
  • 175
  • 4
  • 19