【问题标题】:Return the difference between two DateTime objects using KnpTimeBundle使用 KnpTimeBundle 返回两个 DateTime 对象之间的差异
【发布时间】:2017-06-03 19:43:39
【问题描述】:

我正在尝试使用 KnpTimeBundle 获取之前的日期时间。
正如文档所说,我需要使用辅助类来访问 diff() 函数:
看看我的controller.php:

use Knp\Bundle\TimeBundle\Templating\Helper as Helper;

/**
 * @Route("/test",name="test")
 * @Method({"GET","POST"})
 */
public function testAction(Request $request){
$date = new \DateTime("now");
$h=new Helper();// here i got a 404 error
$ago=$h->diff($date);
return $this->render('test.html.twig', array());
}

但是通过这种方式调用 Helper 类对我不起作用,任何人都可以给我正确的方法来做这个把戏。

【问题讨论】:

    标签: symfony symfony-1.4 symfony-3.2


    【解决方案1】:

    我只是创建自己的服务,不需要捆绑:

    <?php
    namespace AppBundle\Services;
    
    class Helpers {
    public function pluralize( $count, $text ) 
    { 
        return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
    }
    
    function ago( $datetime )
    {
        $interval = date_create('now')->diff( $datetime );
        $suffix = ( $interval->invert ? ' ago' : '' );
        if ( $v = $interval->y >= 1 ) return $this->pluralize( $interval->y, 'year' ) . $suffix;
        if ( $v = $interval->m >= 1 ) return $this->pluralize( $interval->m, 'month' ) . $suffix;
        if ( $v = $interval->d >= 1 ) return $this->pluralize( $interval->d, 'day' ) . $suffix;
        if ( $v = $interval->h >= 1 ) return $this->pluralize( $interval->h, 'hour' ) . $suffix;
        if ( $v = $interval->i >= 1 ) return $this->pluralize( $interval->i, 'minute' ) . $suffix;
        return $this->pluralize( $interval->s, 'second' ) . $suffix;
    }  
    

    在我的 services.yml 中: 服务:

    app.helpers:
        class: AppBundle\Services\Helpers
        arguments: [ "@doctrine.orm.entity_manager" , "@service_container" ]
    

    然后我刚刚打电话:

    $helpers = $this->get("app.helpers");
    $helpers->ago($date);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 2019-11-27
      相关资源
      最近更新 更多