douzhechi2435 2015-01-02 22:50
浏览 33

Twig datetime过滤器可以隐藏午夜时间

Given some date value, I would like to display the date with some given format using Twig. http://twig.sensiolabs.org/doc/filters/date.html provides most of this functionality.

Now, I would like to go one step forward, and if somedate is just equal to something like 2015-01-21 00:00:00 (i.e. midnight), not to display the time but just the date.

I came up with a partial solution where {{ somedate|datetime(true) }} is used to display the datetime potentially with seconds, however, my solution is weak as the format cannot be modified.

$twig->addFilter(new Twig_SimpleFilter('datetime', function ($d,$s=null) {
    $f='m/d/Y'.((strlen($d)==19 && substr($d, -8)!='00:00:00')?' g:i'.(($s)?':s':null).' A':null);
    $date = new DateTime($d);
    return $date->format($f);
}));

I would like to modify the filter so that a format is provided such as {{ data.bid_date|datetime("m/d/Y g:i A") }}, and the datetime is displayed using the given format unless it is midnight in which only the date is showing.

How is this best accomplished?

  • 写回答

2条回答 默认 最新

  • dsaj20411 2015-01-02 22:58
    关注

    you could do something where the date is passed in separately to the time,

    datetime("m/d/Y", "g:i A")
    

    and then mod the current timestamp by 86400 (one day in seconds) and if it's 0, then you know it's midnight and you can display the "time" param instead of just the date param.

    pseudocode:

    datetime(ts, day, time):
        if (ts % 86400 == 0):
            return format_ts(ts, day)
        else:
            return format_ts(ts, day + " " + time)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程