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 - new Date();
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");
}
});
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function updateDays(expDate, e) {
var now = new Date();
var startDate = now.toDateString('dd/MM/yyyy');
var expire = new Date(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?"