0

I have a problem with dateFormat when it is in function beforeShowDay.

I am using datapicker jQuery DataPicker from https://api.jqueryui.com/datepicker/.

I would like it to check the dates and change the colors. I set the dataPicker dataFormat,but not working. When is mm-dd-yy then it working, but I wish it would work when it's set yy-mm-dd. how can I fix it? This is my script:

 <style>
.event a {
    background-color: lightgreen !important;
    color: #ffffff !important;
}

</style>
<script>

 $( function() {
    var eventDates = {};
    eventDates[ new Date( '2020-11-09' )] = new Date( '2020-11-09' ); //this not working
    eventDates[ new Date( '2020-11-10' )] = new Date( '2020-11-10' ); //this not working

    eventDates[ new Date( '11-09-2020' )] = new Date( '11/09/2020' ); //this working
     eventDates[ new Date( '11-10-2020' )] = new Date( '11/10/2020' ); //this working

    $( "#datepicker" ).datepicker({
        dateFormat: 'yy-mm-dd',
        altField: "#alternate",
        altFormat: "yy-mm-dd",
      beforeShowDay: function( date ) {

            var highlight = eventDates[date];

            if( highlight) {
              
                 return [true, "event", 'Text'];
            } 
            else {
               
                 return [true, '', ''];
                }
            }
   
    });
  } );
  </script>
1
  • 2020-11-09 is parsed as UTC, 11/09/2020 probably as local m/y/d. 11-09-2020 is parsed as an invalid date in Safari at least and who knows what in other implementations. See Why does Date.parse give incorrect results?
    – RobG
    Commented Nov 9, 2020 at 3:04

2 Answers 2

0

Try to use this format: yyyy-mm-dd

0

Consider the following example.

$(function() {
  var eDates = [];
  var dF = 'yy-mm-dd';

  eDates.push('2020-11-09');
  eDates.push('2020-11-10');

  $("#datepicker").datepicker({
    dateFormat: dF,
    beforeShowDay: function(date) {
      var fDate = $.datepicker.formatDate(dF, date);
      var result = [
        true,
        "",
        ""
      ];
      if (eDates.indexOf(fDate) >= 0) {
        result[1] = "event";
        result[2] = "Event Text";
      }
      return result;
    }
  });
});
.ui-datepicker-calendar td.event a {
  background-color: lightgreen;
  color: #ffffff;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input type="text" id="datepicker" />

You can use $.datepicker.formatDate( format, date, options ) to format a date object to a String. This can make it a lot easier to compare.

See More: https://api.jqueryui.com/datepicker/

Not the answer you're looking for? Browse other questions tagged or ask your own question.