dpkt17803 2015-05-31 04:27
浏览 34

php中的日期差异自定义输出

Here is my php code. It is working fine.

<?php
........
    $cdt1 = Date("Y-m-d H:i:s");            

    $last_seen = "2015-05-20 12:15:20";

    $datetime22 = new DateTime($cdt1);

    $datetime11 = new DateTime($last_seen);

    $interval1 = $datetime11->diff($datetime22);

echo $interval1->format('%y years %m months and %d days %H hours, %i min and %s sec ');
.........
?>

It is giving me output like this. 0 years 0 months 0 days 00 hours 1 min and 52 sec. Something like that.

I want

  if year is 0 then year doesn't show.
  if month is 0 then month doesn't show.
  if days is 0 then days doesn't show.
  same for hour and min as well.

e.g if difference of time is 1 hour 24 min 30 sec then it should appear like 1 hour 24 min 30 sec. I don't want year/month/days if they are 0.

Please advise.

  • 写回答

3条回答 默认 最新

  • doumou8527 2015-05-31 04:51
    关注

    One option could be using a regular expression:

    $date = $interval1->format('%y years %m months and %d days %H hours, %i min and %s sec ');
    
    $replaced = false;
    while ($replaced)
    {
        $date = preg_replace('/^(0 [a-z]+)/', '', ltrim($date, " ,and"), 1, $replaced);
    }
    

    Notice the ^ character showing the beginning of the regular expression, the fourth parameter to make only one replacement at a time and the fith one to use it as a bool (integer) flag in the while.

    评论

报告相同问题?

悬赏问题

  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改