Reputation: 13
I have two dates. I would like to know a) the number of full months between the two dates and b) the number of days after subtracting the full months.
Essentially what DATEDIF(start_date, end_date, "m")
and DATEDIF(start_date, end_date, "md")
would do if entered as a formula in Google Sheets.
Example: Start date is 18 November 2015 End date is 3 March 2016
The number of full months between the two dates is 3. The number of days after subtracting the full months is 12 + 3 = 15.
Does anyone have a solution how to calculate this in Google Apps Script?
Upvotes: 0
Views: 2375
Reputation: 18717
To get the number of days after subtracting the full months, use this code:
function getNumberOfDaysBetweenTwoDatesSubstractFullMonths(startDate, endDate) {
var startDay = startDate.getDate();
var startMonth = startDate.getMonth();
var startYear = startDate.getYear();
var endDay = endDate.getDate();
var startNumber = daysInMonth(startMonth, startYear) - startDay;
var endNumber = endDay;
return startNumber + endNumber;
}
function daysInMonth(month, year) {
return new Date(year, month + 1, 0).getDate();
}
To check this in Google Sheets Script:
function TEST_days() {
var d1 = new Date('18 November 2015');
var d2 = new Date('3 March 2016');
Logger.log(getNumberOfDaysBetweenTwoDatesSubstractFullMonths(d1, d2));
}
Upvotes: 2