Subtract 2 dates and return Month
I have been trying to find this information but have been unable to. I have an HTML form that has 2 fields (todays_date, mat_date) that have been formatted to accept a date in this format (MM/DD/YY). I need to get the difference between these two dates (mat_date - todays_date) returned in the number of months (1st day of the month is the same as the last day) and this needs to be calculated/returned in once the total_mths field is tabed into or clicked on. Any help is appreciated.
You just need to create two Date objects by fields' values, then you can easily find difference in milliseconds and then convert it to minutes, hours or days simply by division:
However if you want to find out difference in months (month is not determined period of time) you need to decide what you mean by month.
var diff = new Date(field1.value).getTime() - new Date(field2.value).getTime();
// or the same
var diff = Date.parse(field1.value) - Date.parse(field2.value);
var days = diff / 1000 / 60 / 60 / 24;
For some applications you prefer to think of month as of 30.44 days (financial, statistics etc) or even about 21.7 working days.
In other cases, when you want to count the number of real months, your task is even simpler - get years and months from both dates and subtract them:
The line which is commented allows you to add compensation (about 15 days) to larger date so that error of result is -0.5...+0.5 instead of -1..0.
var d1 = new Date(field1.value);
var d2 = new Date(field2.value);
// d1.setTime(d1.getTime() + 15.22 * 24 * 60 * 60 * 1000);
var diff = d1.getYear() * 12 + d1 .getMonth() - d2.getYear() * 12 - d2.getMonth();
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)