2017-06-03 205 views
0

我试图使用KnpTimeBundle得到以前的日期时间。
作为文件建立说,我需要使用辅助类来接取DIFF()功能:
看看我Controller.php这样:使用KnpTimeBundle返回两个DateTime对象之间的差异

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()); 
} 

但是通过这种方式didnt调用Helper类为我工作,任何人都可以给我正确的方法来实现这个诀窍。

回答

0

我刚刚创建自己的服务不需要捆绑:

<?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);