开发者

Number of years passed - Consider leap year

开发者 https://www.devze.com 2022-12-15 23:01 出处:网络
In our HR system, we want to calculate the number of years the employee has served the company. What we have is the 开发者_如何学Gojoining date in TIMESTAMP column.

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

What we have is the 开发者_如何学Gojoining 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.


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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消