duanliang9288 2010-11-14 06:35 采纳率: 100%
浏览 25
已采纳

找出2个日期之间的差异

I made this and needed some help tweaking it so that it gives the proper outcome

function daysDifference($end){
    //$start = "2007-03-24";
    //$end = "2009-06-26";
    $now = date("Y-m-d");
    $e = (is_string($end) ? strtotime($end) : $end);

    $diff = abs($e - strtotime($now));

    $years = floor($diff / (365 * 60 * 60 * 24));
    $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
    $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24)/ (60 * 60 *24));

    return ($years == 0 ? '' : ($years == 1 ? $years . ' year ' : $years . ' years ')) . ($months == 0 ? '' : ($months == 1 ? $months . ' month ' : $months . ' months ')) . ($days == 0 ? '' : ($days == 1 ? $days . ' day ' : $days . ' days '));
}

$end is being pulled from my database so there is checks to see if its a string or a date already.

$e now can be used, but when I tried to subtract $now from $e I get funny results

for instance:

$now being today the 13th and $e being an end date for a project, it's suppose to give me what I need... right?

Where I'm suppose to get say 12 days remaining, I get 1 year 12 days.

and where $e = 0000-00-00 (in case the user didn't input an end date), I get 40 years 10 months and 26 days remaining.

I tried alot of different variations to my calculations but I keep getting nowhere.

  • 写回答

2条回答 默认 最新

  • duanba5777 2010-11-14 06:41
    关注

    Store real dates, not strings, and you can just ask the database for the difference.

    SELECT DATEDIFF(CURRENT_DATE, end) FROM table
    

    If you just go dividing things by 365 you won't get accurate results. Not every year has 365 days.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大