2013-10-02 123 views
0

我有此$date數組:Echo在時間戳格式的陣列/日期時間對象

Array 
(
[start] => DateTime Object 
    (
     [date] => 2013-09-19 00:00:00 
     [timezone_type] => 3 
     [timezone] => Europe/London 
    ) 

[end] => DateTime Object 
    (
     [date] => 2013-10-20 23:59:00 
     [timezone_type] => 3 
     [timezone] => Europe/London 
    ) 

) 

欲迴響在時間戳格式(2013年9月19日00:00:00) 開始日期值我試圖echo $date['start']->date->getTimestamp();但它返回我這個錯誤:Fatal error: Call to a member function getTimestamp() on a non-object in ...

回答

3

您正在尋找:

echo $date['start']->format('Y-m-d H:i:s'); 

。我相信檢查所有可能的墊子here, on the manual page
不要讓垃圾桶欺騙你,DateTime對象還沒有公開date屬性,as you can see here。但是,它有一個getTimestamp方法,它返回一個int,就像time()一樣,cf the manual
你可以使用任何預定義的常量(所有字符串,代表標準格式),例如:

echo $data['end']->format(DateTime::W3C);//echoes Y-m-dTH:i:s+01:00) 
//or, a cookie-formatted time: 
echo $data['end']->format(DateTime::COOKIE);//Wednesday, 02-Oct-13 12:42:01 GMT 

:我基於+01:00GMT上轉儲,顯示倫敦爲你的時區...

所以:

$now = new DateTime; 
$timestamp = time(); 
echo $now->getTimetamp(), ' ~= ', $now;//give or take, it might be 1 second less 
echo $now->format('c'), ' or ', $now->format('Y-m-d H:i:s'); 

閱讀手冊,播放醃肉次用了一段時間,你很快就會發現DateTime類,並且它的所有相關類(如DateIntervalDateTimeImmutable等(full list here))非常好用的東西確實是......

我已經把以codepad爲例,這裏是代碼:

$date = new DateTime('now', new DateTimeZone('Europe/London')); 
$now = time(); 
if (!method_exists($date, 'getTimestamp')) 
{//codepad runs <PHP5.3, so getTimestamp method isn't implemented 
    class MyDate extends DateTime 
    {//bad practice, extending core objects, but just as an example: 
     const MY_DATE_FORMAT = 'Y-m-d H:i:s'; 
     const MY_DATE_TIMESTAMP = 'U'; 
     public function __construct(DateTime $date) 
     { 
      parent::__construct($date->format(self::MY_DATE_FORMAT), $date->getTimezone()); 
     } 
     /** 
     * Add getTimestamp method, for >5.3 
     * @return int 
     **/ 
     public function getTimestamp() 
     {//immediatly go to parent, don't use child format method (faster) 
      return (int) parent::format(self::MY_DATE_TIMESTAMP); 
     } 
     /** 
     * override format method, sets default value for format 
     * @return string 
     **/ 
     public function format($format = self::MY_FORMAT) 
     {//just as an example, have a default format 
      return parent::format($format); 
     } 
    } 
    $date = new MyDate($date); 
} 
echo $date->format(DateTime::W3C), PHP_EOL 
    ,$date->format(DateTime::COOKIE), PHP_EOL 
    ,$date->getTimestamp(), ' ~= ', $now; 
+0

哇,非常感謝你。這確實幫助了我。 問題解決了! – KouiK

相關問題