Twig框架和日期时间错误


Twig framework and datetime errors

我正在Apache 2.28上运行一个由PHP/MMySQL提供支持的事件站点。我可以根据http://devzone.zend.com/article/13633.

对于localhost上的这个网站,我使用的是www.twitch项目中提到的Twig框架。org

内容从本地MySQL数据库中提取:

我的代码:

    <html>
  <head>
    <style type="text/css">
      table {
        border-collapse: collapse;
      }        
      tr.heading {      
        font-weight: bolder;
      }        
      td {
        border: 1px solid black;
        padding: 0 0.5em;
      }    
    </style>  
  </head>
  <body>
    <h2>Events</h2>
    <table>
      <tr class="heading">
        <td>Event time</td>
        <td>Event name</td>
      </tr> 
      {% for d in data %}
      <tr>
        <td>{{ d.evtime|escape }}</td>
        <td>{{ d.evname|escape }}</td>
      </tr> 
      {% endfor %}
    </table>
  </body>
</html>

//PHP文件位于下方

    <?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
  $dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'MYPASS');
} catch (PDOException $e) {
  echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
  // execute SELECT query
  // store each row as an object
  $sql = "SELECT * FROM myeventdb";
  $sth = $dbh->query($sql);
  while ($row = $sth->fetchObject()) {
    $data[] = $row;
  }
  // close connection, clean up
  unset($dbh); 
  // define template directory location
  $loader = new Twig_Loader_Filesystem('templates');
  // initialize Twig environment
  $twig = new Twig_Environment($loader);
  // load template
  $template = $twig->loadTemplate('countries.tmpl');
  // set template variables
  // render template
  echo $template->render(array (
    'data' => $data
  ));
} catch (Exception $e) {
  die ('ERROR: ' . $e->getMessage());
}
?>

但是,我无法将事件的日期时间显示为:下午1:30地理课

相反,它显示为13:30:00地理类

为什么在Twig语法中会出现这种情况,我需要什么来修复它?我对此还很陌生,我浏览了一下文档,但网站上没有太多关于它的内容

干杯。

所以脚本显示的是13:30:00,因为这是数据库中的内容——您没有在任何地方格式化日期。

在您的Twig模板中,您可以使用date过滤器根据PHP date函数格式设置日期:

{{ d.evtime|date('g:ia')|escape }}

如果您想事先进行格式化,只需使用datestrtotime:的组合

$formatted_time = date('g:ia',strtotime($unformatted_time));