tags:

views:

93

answers:

2

In our HR system, we want to calculate the number of years the employee has served the company.

What we have is the joining date in TIMESTAMP column.

What I am doing is:

$timeNow = time(); // current time
$joinDate = strtotime($users->fields['date_of_joining']); // from database
$servicePeriod = $timeNow - $joinDate; // in seconds
$servicePeriod = $servicePeriod / 31570560; // in years

But will this take the leap years into consideration? If an employee joined in Feb 27 of a leap year and if we check the status next year by March 1, he should still be reported as served for 1 year and not 1 year and 1 day.

Any ideas on this? Thanks.

+7  A: 

Your method seems like an unnecessarily roundabout way to calculate this. How about this (pseudocode):

years = current_date.year - start_date.year
if current_date.mmdd < start_date.mmdd:
    years = years - 1
Greg Hewgill
That's how I calculate age too.
Esteban Araya
That's one bit of excellent logic! Thank you so much!
Nirmal
A: 

You have counted with 365.4 days in a year which is obviously wrong. If you change that to 365.26 (31558464), leap years will be automatically included in the long run, but not if the period is shorter than 4 years. This is in your own advantage, but not in your employees'.

Also, add a last line to round the number down to completed days:

$servicePeriod = floor($servicePeriod);
Emil Vikström
I particularly like the way you chastised the OP for choosing the wrong value then went ahead and used your *own* wrong value :-) It's 365.2425 which takes care of the 4/100/400 rules.
paxdiablo
paxdiablo, the best value to use nowadays is probably 365.25 anyway :-)
Emil Vikström