-1
    var dates = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["ph"]));
    //dates[0] = 16-09-2017
    //date = 09/16/2017
    $('#StartDate').datepicker({
        dateFormat: JsDateFormat,
        autoclose: true,
        beforeShowDay: function (date) {
            for (var i = 0; i < dates.length; i++) {
                if (new Date(dates[i]).toString() == date.toString()) {
                    console.log(date);
                    return [true, 'ui-state-highlight highlight-red', name[i]];
                }
            }
            return [true];
        }
    });

how to change the date format from '09/16/2017' to '16-09-2017'? i had tried new Date('dd-M-yy', date).toString() - not working date.toString('dd-M-yy') - not working

Jessica
  • 23
  • 3
  • 14

3 Answers3

1

Since you're using datepicker you can use $.datepicker.formatDate

Here is a snippet using formatDate to compare the dates in the array:

var dates = ['10-10-2017', '25-10-2017', '29-10-2017'];
$('#StartDate').datepicker({
    dateFormat: "d/m/yy",
    autoclose: true,
    beforeShowDay: function (date) {
      for (var i = 0; i < dates.length; i++) {
        if (dates[i] == $.datepicker.formatDate('dd-mm-yy', date)) {
          console.log(date);
          return [true, 'ui-state-highlight highlight-red', name[i]];
        }
      }
      return [true];
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<input type="text" id="StartDate" name="StartDate"/>
kakamg0
  • 1,096
  • 5
  • 12
0

ViewData["ph"] the date time will be converted to string with culture of the server in which the application is running so be sure to convert with this format in the server and assign to the ViewData.

If value passed to JsonConvert is a type of Date object then make use of the formating parameter to the method SerializeObject

JsonConvert.SerializeObject(this, Formatting.None, new IsoDateTimeConverter() { 
             DateTimeFormat = "dd-M-yy" });

If you want to convert date to string refer the answer provide by @rahul mr for all browsers

   function formattedDate(d) {
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var year = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return day + '/' + month + '/' + year;
}
Krishjs
  • 358
  • 2
  • 17
-1
function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

this function returns date in format you needed

Rahul
  • 462
  • 1
  • 4
  • 16