-2

I have input control for date field. I wish to date format like 2/2/2019 .In below code output is : 02/02/2019

Sample Code:

var date = new Date($('#AppointmentDate').val());
var formatted = ('00' + date.getDate()).slice(-2) + '/' + ('00' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear();

console.log(formatted);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="02/02/19 12:00:00 AM">
nur islam
  • 67
  • 8
  • Possible duplicate of [Remove leading zeroes in datestring](https://stackoverflow.com/questions/8897298/remove-leading-zeroes-in-datestring) – jtylerm Jun 03 '19 at 13:22
  • Possible duplicate of [Get String in YYYYMMDD format from JS date object?](https://stackoverflow.com/questions/3066586/get-string-in-yyyymmdd-format-from-js-date-object) – dganenco Jun 03 '19 at 13:23
  • No it isn't a dublicate of the links you provided. The first link is asking for a replacement of zeros for an already given string. The second one is just asking for how to get a string out of an object. – Aaron3219 Jun 03 '19 at 13:25

2 Answers2

2

Your code appends 0's if the date is smaller than 10. Simply remove that code:

var date = new Date($('#AppointmentDate').val());
var formatDate =getFormattedDate(date);
console.log(formatDate);

function getFormattedDate(date) {
  var year = date.getFullYear();

  var month = (1 + date.getMonth()).toString();

  var day = date.getDate().toString();
  
  return month + '/' + day + '/' + year;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="2/2/19 12:00:00 AM">

To your edit, again, remove the code that is adding the zero's:

var date = new Date($('#AppointmentDate').val());
var formatted = ('' + date.getDate()).slice(-2) + '/' + ('' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear();

console.log(formatted);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="02/02/19 12:00:00 AM">
Kobe
  • 6,226
  • 1
  • 14
  • 35
-1

you could use parseInt to remove preceeding zeros

stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69