duanjia6959 2014-11-14 11:45
浏览 10
已采纳

PHP时间过去了,在秒之前删除“和”

So, I've got this working code which converts a MySQL date to UNIX Timestamp and subtracts it from the current date() to show a "time elapsed since X"-like timer. (the part which takes the date from database is missing since it's in another script)

    <?php 
    function time_elapsed($secs){
        $bit = array(
            ' year'        => $secs / 31556926 % 12,
            ' week'        => $secs / 604800 % 52,
            ' day'        => $secs / 86400 % 7,
            ' hour'        => $secs / 3600 % 24,
            ' minute'    => $secs / 60 % 60,
            ' second'    => $secs % 60
            );
        foreach($bit as $k => $v){
            if($v > 1)$ret[] = $v . $k . 's';
            if($v == 1)$ret[] = $v . $k;
            }
        array_splice($ret, count($ret)-1, 0, 'and');
        $ret[] = 'ago.';

        return join(' ', $ret);
        }

    $nowtime = time() + 10; //add 10s to avoid error
    $oldtime = strtotime($mysqltime2);

    $time_elapsed = time_elapsed($nowtime-$oldtime)."
";
    echo wordwrap($time_elapsed,35,"<br />
"); //split long line
    ?>

I managed to fix an error reporting missing array or something if the script was executed at the same time of the MySQL date by adding 10 seconds to the current timestamp.

Another issue I have is that the script shows "and X seconds" even if there aren't minutes/hours/days/etc before it. E.g. "and X seconds" "Y minutes and X seconds" "Z hours Y minutes and X seconds" "N days Z hours Y minutes and X seconds"

I want to remove the "and" before seconds ONLY if there's no minutes/hours/etc before it.

Any tip on how to fix this?

  • 写回答

3条回答 默认 最新

  • dongque4778 2014-11-14 11:54
    关注

    You could only splice when needed:

    if( count($ret) > 1 ) {
        array_splice($ret, count($ret)-1, 0, 'and');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计