Let’s say you have two text-boxes that show dates, and you need to get a difference between the two. There is no built-in JavaScript function to calculate the difference but you can easily accomplish it using a few JavaScript functions.
Let’s assume that a date is represented in the following format: mm/dd/yyyy.
First we need to convert this string into a JavaScript Date object. Here is a function that does that.
function convertToDate(str){
var arr = str.split(’/');
var year = arr[2];
var day = arr[1];
var month = arr[0]-1; //month argument starts with 0
return new Date(year, month, day, 0,0,0);
}
Pass a string to the function and get a Date object back. You may need to modify it depending on your date format and separator used.
Now we can get 2 strings from text-box values that have the following ids : startDate and endDate, and convert them to Date objects.
var start = document.getElementById ("startDate");
var end = document.getElementById ("endDate");
var d1 = convertToDate(start.value);
var d2 = convertToDate(end.value);
The following statement calculates the difference between 2 Date objects in milliseconds:
var span = d2.getTime()- d1.getTime();
Let’s calculate the number of milliseconds in a day:
var day = 1000*60*60*24;
And finally, the representation of the difference in days:
var days = parseInt(span/day);