douniangliao4327 2016-01-18 10:09
浏览 30
已采纳

如何以良好的格式显示剩余日期?

I am creating a value that shows me the remaining time from a date until now:

$date=date_create(date('Y-m-d H:i:s', strtotime($mydate)));
$curdate=date_create(date("Y-m-d H:i:s"));
$diff=date_diff($date,$curdate);
$diff1= $diff->format("%y years %m months %d days");

The result in this case is: 0 years 0 months 27 days

What I would like to do is, show only years or months if they are not 0. So in this case I would only like to get the result 27 days. And if it is only one day left, then it shows 1 days but it should show 1 day (so if the result is 1 show singular).

I tried something like this, but it didn't work:

$diff1= $diff->format(if("%y" !=0){"%y years"}); if("%m" !=0){"%m months"}) %d days");
  • 写回答

2条回答 默认 最新

  • dregvw1801 2016-01-18 10:25
    关注

    date_diff returns an instance of the DateInterval class which has the class variables $y, $m and $d for the corresponding years, months and days.

    As such what you were trying to achieve can still be done using these variables:

    $diff=date_diff($date,$curdate);
    $format = '';
    if ($diff->y > 0) {
         $format = '%y years';
    } else if ($diff->m > 0) {
         $format = '%m months';
    } else {
         $format = '%d days';
    }
    $diff1 = $diff->format($format);
    

    The elimination of the s in years/months/days is left up to the OP.

    (edited)

    In this case only one category will printed, but to get more than one at a time, modify the 'if-else' to individual 'if' and concatenation with previous categories,

    if ($diff->y > 0) {
         $format = '%y years ';
    }
    if ($diff->m > 0) {
         $format .= '%m months ';
    }
    if ($diff->d > 0) {
         $format .= '%d days';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题