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
                                alert(‘End Date must be greater than Start Date.’);
                                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)
                                                SDuration = “”;
                                document.getElementById(“_Datatask_cduration”).innerText = SDuration;
                return valid;