2012-01-08 122 views
0

我從外地創建日期和時間,像這樣的格式2011-3-10 17:26:50進賬,我想轉換爲這種格式March 13, 2010我怎麼能做到這一點用PHP或CakePHP的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; ?> 

回答

2

我想你的意思是 「取」,如從MySQL檢索。最簡單的/最快的(同時也是最喜歡炸燬,踢你的狗)是簡單地做

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

感謝馬克·B檢查是工作 – user1080247 2012-01-08 06:09:38

+0

如果你不想踢你的狗,使用['DateTime'](http://php.net/manual/en/book.datetime .PHP)。 – 2012-01-08 08:22:16

0

這樣的事情? 我猜你的日期時間格式。你可能需要調整它。

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

2

PHP有多種格式(包括功能strtotime($string),這將需要日期/時間字符串MySQL的日期時間格式)並將其轉換爲Unix時間戳整數(從1970-01-01 00:00:00 UTC開始的秒數)。然後,您可以使用date('F j, Y', $time)將該整數轉換爲您想要的任何字符串表示形式,使用找到的令牌here

另外兩個考慮事項是本地化和時區知曉。我不會進入第一個,因爲它看起來並不需要它,但是在時區很重要的地方,使用PHP的DateTime類可以更容易,您可以閱讀關於 [here]的更多信息。這裏有一個例子:

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

這將解決這個問題:

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

你可以很容易地使用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文檔。

感謝,

相關問題