cpl
cpl

Reputation: 689

Date changes when setting value

I'm facing a strange problem, I have a function to get the current date. It may not be the best, but it's ok. I then use the function to set the value of a hidden input:

function gettoday() {
  var d = new Date();
  var month = d.getMonth() + 1;
  var day = d.getDate();

  var out = (day < 10 ? '0' : '') + day + '/' +
    (month < 10 ? '0' : '') + month + '/' +
    d.getFullYear();
  return out;
}

something.attr('value', String(gettoday()));

When I do so the date becomes 31/12/1969. The gettoday() function returns the correct date. Any ideas what could be happening? I tried debugging the call but nothing happens there. The same happens in Chrome or Firefox. Thanks!

Upvotes: 1

Views: 55

Answers (1)

Shridhar Sharma
Shridhar Sharma

Reputation: 2387

You should set the value using val in yyyy-mm-dd format, try the following snippet

function gettoday() {
  var d = new Date();

  var month = d.getMonth() + 1;
  var day = d.getDate();

  var out = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
  return out;
}

$('input').val(gettoday());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date">

Upvotes: 1

Related Questions