dongpin6941 2014-09-01 17:05
浏览 24
已采纳

如何在所有单位(y,m,d,h,i,s)中得出两个日期时间之间的差异?

I want to get the difference between two datetime, so if the difference is just seconds, I want to echo the seconds only and so on, for example the output should be something like:

5 seconds ago

5 minutes ago

5 hours ago ...

here is my code that I used but it give me the days only:

$date1 = new DateTime(date('Y-m-d', strtotime("2013-08-07 13:00:00")));
$date2 = new DateTime(date('Y-m-d', strtotime("2012-08-08 12:00:00")));
echo $date1->diff($date2)->days;

and this code is giving me what I want but all at once:

$x = new DateTime($career->postdate);
$interval = $x->diff(new DateTime(date('Y-m-d H:i:s')));
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %S seconds');
echo $elapsed;

I know that I can play with the ouput string in the second code to achieve my goal, but its not a preferred way, so how I can do that in the best way ?

  • 写回答

2条回答 默认 最新

  • duandi8838 2014-09-01 17:43
    关注
    function x($i, $s) {
        return ($i>0 ? $i.$s : "");
    }   
    
    function f($int) {
        $ret = x($int->y, 'y ');
        $ret.= x($int->m, 'm ');
        $ret.= x($int->d, 'd ');
        $ret.= x($int->h, 'h ');
        $ret.= x($int->i, 'min ');
        $ret.= x($int->s, 's ');
        return $ret;
    }
    
    $date1 = new DateTime("2013-08-08 13:00:00");
    $date2 = new DateTime("2012-08-06 12:30:00");
    $interval = $date1->diff($date2);
    echo f($interval);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集