JavaScript to Calculate days difference between dates (Duration)

By | June 1, 2012

Handling the date fields is usually a tricky part in development work. Sometimes it is termed as programmer’s nightmare as lots of formatting and validation complications are involved when working on the same from client side script. Recently we had a requirement where we had to get the duration between 2 dates and display the same in a third field. We usually get a lot of knowledge base to achieve the same from server side but we had to achieve the same from client side script. This needed to work when the fields were populated i.e. during onchange.
The below script helps us to achieve this functionality. This code needs to be added in the Onchangescript block of both the date fields.
//’Calculate duration value
function CalculateDuration()
{
                //’Form message
                var sMessage = “”;
                var valid = true;
                //’Get value of start date
                var dStartDate = new String(document.EntryForm.task_cstartdate.value);
                if(dStartDate ==”” || dStartDate ==”null” || dStartDate ==”undefined”) dStartDate =””;
                //’Get value of end date
                var dEndDate = new String(document.EntryForm.task_cenddate.value);
                if(dEndDate ==”” || dEndDate ==”null” || dEndDate ==”undefined”) dEndDate =””;
/* Please note that this script works if the user date format is in mm/dd/yyyy, else make sure the date needs to be changed to this format before using this script. */
                //’Perform validations
                if(dStartDate>dEndDate)
                {
                                alert(‘End Date must be greater than Start Date.’);
                                valid=false;
                }
                else
                {
                                var SDuration = 0;
                                //Set 1 day in milliseconds
                                var one_day=1000*60*60*24
                                //’calculate duration
                                SDuration = (dEndDate.getTime()-dStartDate.getTime())/one_day;
                                SDuration = new String(SDuration)
                                if(SDuration==”NaN”)
                                                SDuration = “”;
                                document.getElementById(“_Datatask_cduration”).innerText = SDuration;
                                document.EntryForm._HIDDENtask_cduration.value=SDuration;
                                valid=true;
                }
                return valid;
}