Calculate Date Range

Introduction

Calculating the duration between two dates can be crucial for various applications, from scheduling to reporting. This guide explains how to compute the number of days between two dates using JavaScript. By integrating this functionality, you can easily track and manage date ranges within your forms.

How does it work?

The provided JavaScript code listens for changes in the Datepicker fields for from and to dates. When either date is updated, the code calculates the difference in days between the two dates and displays this duration in a separate field. The calculation is based on the millisecond difference between the two dates divided by the number of milliseconds in a day.

Code:

$('input[name="fromDatepicker"], input[name="toDatepicker"]').change( function(){
      d1 = $('input[name="fromDatepicker"]').datepicker('getDate');
      d2 = $('input[name="toDatepicker"]').datepicker('getDate');
      diff = 0;
      if (d1 && d2) {
            diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
      }
      $('input[name=days]').val(diff);
});

Download sample app

Download the demo app for Calculate Date Range:
Created by Julieth Last modified by Aadrian on Dec 13, 2024