Difference in days between two datesWe will take input from two calendars and find out the difference in days between them. First we will display two interlined calendars each connected to one textbox. User can select dates from these calendars.
Interlinked CalendarsThese two calendars are interlinked so the selection of first one will set the lower limit for the second one. The selection of second one will set the upper limit for the first one. Once the user select the dates using two calendars , our script should execute and display the result. Here our full code of calculation for date difference will be triggered once the second calendar is selected or changed. You can change this to display on click of a button or any other event triggered by user.
We will read the selected date values first and store in a variable.
We will break the date variable by using split command to create an array with three elements. The first element will store date , second element will store month and third element will store Year. Based on the date format you used in the calendar this will change. If you are in mm-dd-yy format then first element will store month , second element will store date and third element will store year. Using this we will create date object.
We will create Date object using these elements of the array. For this we require elements in the order of YYYY, mm, dd format.
We will subtract month by 1 as all calendar months are represented between 0 to 11 ( not 1 to 12 ). For example month of March should be 2 ( not 3 ) . Let us crate date object now.
By using getTime() function we will first convert the date collected from the calendars to milliseconds. This is the value passed in milliseconds from Jan 1st 1970.
Same way we will find out the mill seconds value generated for second date value.
Then we will find out the difference between two dates using this mill second values. We will find out number of mill seconds in a single day by using mill seconds, seconds, minutes and hours. Instead of calculating we can directly store the value as 86400000 ( mill seconds in a day )
Now let us find out the difference and then divide by number of mill seconds in a day. The result of this division may contain negative value so we will use math abs function to get the absolute values.
To show the result we have used one div tag and result is posted inside that.