如何将时间格式从数字转换为字符串


how to convert time format from number to string?

我从创建的字段中提取的日期和时间,类似于2011-3-10 17:26:50格式,我想转换为March 13, 2010格式。我如何使用php或cakefp 1.3 做到这一点

     <?php
  $i = 0;
foreach($articles as $$article ):
                 ?>
                <tr>
                    <td><?php echo $article['Article']['title']; ?></td>
                    <td><?php echo $article['Article']['created'];;?></td>
                </tr>
                <?php endforeach; ?>

我想你的意思是"提取",就像从MySQL检索一样。最简单/最快的(但也最喜欢炸开并踢你的狗)就是简单地进行

$timestamp = strtotime($date_from_database);
$formatted = date('F j, Y', $timestamp);

PHP有一个函数strtotime($string),它将采用各种格式的日期/时间字符串(包括MySQL的日期时间格式),并将其转换为Unix时间戳整数(自11970-01-01 00:00:00UTC以来的秒数)。然后,您可以使用date('F j, Y', $time)将该整数转换为您想要的任何字符串表示,使用中的令牌

另外两个考虑因素是本地化和时区意识。我不会讨论第一个,因为你似乎不需要它,但在时区很重要的地方,使用PHP的DateTime类会更容易,你可以在这里阅读。这里有一个例子:

<?php
// for example, if you're storing times in UTC in your DB
$dbTimezone = new DateTimeZone('UTC');
// we'll use this for displaying times in the user's timezone.
// for example, my timezone:
$displayTimezone = new DateTimeZone('America/Toronto');
foreach ($articles as $article):
    // Create a timezone-aware DateTime object from your article's creation date
    $dt = new DateTime($article['Article']['create'], $dbTimezone);
    $dt->setTimezone($displayTimezone);
    echo $dt->format('F j, Y');
endforeach;

这样的东西?我猜你的约会时间格式。你可能需要调整一下。

echo date('F d, Y',date_create_from_format('Y-n-d h:i:s','2011-3-10 17:26:50'));

date_create_from_format

这将解决问题:

$date = date_create_from_format('Y-m-j H:i:s', $article['Article']['created']);
echo date_format($date, 'F d, Y');

您可以轻松使用Cakephp时间帮助程序。

//Add to appcontroller or articles_controller
var $helpers = array('Time');
//Add this to view file
echo $this->Time->niceShort($article['Article']['created']); 

除了niceShort,还有更多的选项可能更适合您的需求。查看CakePHP文档。

谢谢,