PDA

View Full Version : how to convert days to months



ad3d
14th February 2011, 17:53
i have a date of joining of an employee and i want to know till current date how many MONTHS he/she has worked in the company..

if i take months ~= 30 days the answer i get is not accurate..

Can someone plz guide me how can i convert days to MONTHS for above requirement..

Thanx
ad3d

SixDegrees
14th February 2011, 17:57
Unless you know the date of hire or the date of the query, you cannot get an exact answer.

If you know one of those parameters, you simply have to loop over a table of month lengths and add up the results, plus whatever slop remains in the first or final partial month.

This assumes that the period covered is entirely within one year. If not, or if the period spans several years, you will have to perform corrections for leap years as well.

ChrisW67
14th February 2011, 22:20
You could use a better approximation of the number of days in a month. The Gregorian calendar averages to 365.2425 days per year, so an average month is 30.4369 days. For many purposes this is close enough.

If it is for payroll purposes you are better going the long way with something like:


int wholeMonths(const QDate &from, const QDate &to)
{
if (from.isValid() && to.isValid() && to > from) {
int months = qMax(1, (to.year() - from.year() - 1) * 12);
while (from.addMonths(months) <= to)
++months;
return months - 1;
}
else
return 0;
}