Skip to content Skip to sidebar Skip to footer

How Can I Calculate The Number Of Days From Today With Jquery Ui Datepicker?

Good day, I'm having a little trouble with calculating number of days from now to a selected date after selecting a date from jQuery datepicker. I think that the datepicker is chan

Solution 1:

The onSelect event will receive a string in the specified format, which is dd/mm/yy. JavaScript Date.parse method will parse such dates incorrectly, or not parse them at all. The solution is to use parseDate() function built into jQuery ui:

onSelect: function (dateText, inst) {
  var expDate = $.datepicker.parseDate(inst.settings.dateFormat, dateText, inst.settings);
  var diff = expDate - newDate();
  var days = diff / 1000 / 60 / 60 / 24;
  alert( /* ceil, floor, round */ days);
}

Solution 2:

Realised that I need the display to be in jQuery dd/mm/yy (dd/mm/yyyy) format so kept that and did some manipulation to the expDate being passed to the updateDays() method to ensure that the date to be calculated would be handled correctly by JS.

Working script:

$(".datepicker-calc").datepicker({
      dateFormat: "dd/mm/yy",
      changeMonth: true,
      changeYear: true,
      onSelect: function (selectdate, e) {
      var newDate = selectdate.slice(0,2);
      var newMonth = selectdate.slice(4,6);
      if (newMonth < "10") { newMonth = ("0" + newMonth.slice(0,1));};
      var newYear = selectdate.slice(6,11);
      var expDate = newMonth + "/" + newDate + "/" + newYear;
      updateDays(expDate, e);
      $(".datepicker-calc").datepicker("hide");
   }
});

functiontreatAsUTC(date) {
    var result = newDate(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

functionupdateDays(expDate, e) {
    var now = newDate();
    var startDate = now.toDateString('dd/MM/yyyy');
    var expire = newDate(expDate);
    var endDate = expire.toDateString('dd/MM/yyyy');
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    var totalDays = (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
    $('#tbAddDays').val(totalDays);
}

Post a Comment for "How Can I Calculate The Number Of Days From Today With Jquery Ui Datepicker?"