Sham在制作公司小程序的时候,想增加一个功能,就是计算员工入职多少年,多少天,经过几次试验,终于实现了。
此方法是先计算入职的年数,然后再计算天数,不是按实际天数后/365天来算的。
代码如下(采用面向对象的类方法来实现):
<?php
$begindate= "入职日期,年/月/日";
$enddate= "结束日期,年/月/日";
$yeardays = new YEARDays();
$getyeardays = $yeardays -> getyeardays($begindate,$enddate);
echo $getyeardays; //这样就能输出XX年+XX天了
//下面是得出2个日期差的天数的类,begindate 必须早于enddate
class YEARDays{
public function getyeardays($begindate,$enddate){
if(count(explode('/',$begindate))>1){
$newbd = explode('/',$begindate);
}else{
$newbd = explode('-',$begindate);
}
$newby = $newbd[0];
$newbm = $newbd[1];
if(count(explode('/',$enddate))>1){
$newed = explode('/',$enddate);
}else{
$newed = explode('-',$enddate);
}
$newey = $newed[0];
$newem = $newed[1];
if($newby<$newey){
if($newbm<=$newem){
$ys = ($newey - $newby) .'年';
$ds = round((strtotime(date("Y-m-d"))-strtotime($newey.'-'.$newbd[1].'-'.$newbd[2]))/3600/24)+1 . '天';
}else{
if(($newey - $newby-1)>0){
$ys = ($newey - $newby-1).'年';
}else{
$ys = ($newey - $newby-1);
}
$ds = round((strtotime(date("Y-m-d"))-strtotime(($newey-1).'-'.$newbd[1].'-'.$newbd[2]))/3600/24)+1 . '天';
}
}else{
$ys = "";
$ds = round((strtotime(date("Y-m-d"))-strtotime($begindate))/3600/24)+1 . '天'; //得出2个日期相差的天数
}
$yds = $ys .'+'. $ds;
return $yds;
}
}
?>
如果只要计算相差的天数,相对简单点,如下:
<?php
$begindate= "入职日期,年/月/日";
$enddate= "结束日期,年/月/日";
$days = round((strtotime($enddate)-strtotime($begindate))/3600/24) . '天';
//round是取整数天,然后strtotime是将字符串变成时间戳,然后2个时间戳一减,再处于60秒,60分钟,24小时,来得出天数
echo $days;
?>
评论前必须登录!
注册