Select a start date and an end date. The calendars are interlinked so the end date cannot be earlier than the start date, and the script displays the difference in calendar days.
Original demo: difference between two calendar dates →
Choosing the first date sets the second Datepicker's minDate. Choosing the second sets the first Datepicker's maxDate.
$( "#date_picker1" ).datepicker({
dateFormat: "dd-mm-yy",
onSelect: function () {
$( "#date_picker2" ).datepicker(
"option",
"minDate",
$( this ).datepicker( "getDate" )
);
updateDifference();
}
});
$( "#date_picker2" ).datepicker({
dateFormat: "dd-mm-yy",
onSelect: function () {
$( "#date_picker1" ).datepicker(
"option",
"maxDate",
$( this ).datepicker( "getDate" )
);
updateDifference();
}
});
Read the main Datepicker tutorial for additional range examples.
const firstValue = $( "#date_picker1" ).val();
const firstParts = firstValue.split( "-" );
The JavaScript split() tutorial explains string splitting in more detail.
The older example constructed local Date objects and divided elapsed milliseconds by 86,400,000. Around daylight-saving changes that can represent 23 or 25 local hours. For a calendar-day difference, normalize both dates with Date.UTC().
The older version used Date.getTime() to convert each Date object to milliseconds. That remains useful for elapsed-time work; this calendar-day example uses UTC-normalized day values instead.
const firstDayNumber = Date.UTC(
Number( firstParts[2] ),
Number( firstParts[1] ) - 1,
Number( firstParts[0] )
);
const secondValue = $( "#date_picker2" ).val();
const secondParts = secondValue.split( "-" );
const secondDayNumber = Date.UTC(
Number( secondParts[2] ),
Number( secondParts[1] ) - 1,
Number( secondParts[0] )
);
const oneDay = 24 * 60 * 60 * 1000;
const differenceDays = Math.abs(
( secondDayNumber - firstDayNumber ) / oneDay
);
See the JavaScript Math.abs() tutorial for absolute values.
$( "#result" ).text(
"Difference in days: " + differenceDays
);
Using .text() is sufficient because this output is plain text.
function updateDifference() {
const firstValue = $( "#date_picker1" ).val();
const secondValue = $( "#date_picker2" ).val();
if ( !firstValue || !secondValue ) {
return;
}
const firstParts = firstValue.split( "-" );
const secondParts = secondValue.split( "-" );
const firstDayNumber = Date.UTC(
Number( firstParts[2] ),
Number( firstParts[1] ) - 1,
Number( firstParts[0] )
);
const secondDayNumber = Date.UTC(
Number( secondParts[2] ),
Number( secondParts[1] ) - 1,
Number( secondParts[0] )
);
const oneDay = 24 * 60 * 60 * 1000;
const differenceDays = Math.abs(
( secondDayNumber - firstDayNumber ) / oneDay
);
$( "#result" ).text(
"Difference in days: " + differenceDays
);
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.