djb
djb

Reputation: 6011

PHP: DateTime throwing an exception with a legal timestamp

I don't get it:

$ts = strval( $this->get_start_date() ); // retrieve (int) timestamp from database

$time = new DateTime ( $ts ); 
    // throws an exception:  
    //'DateTime::__construct(): Failed to parse time string 
    //(1346284800) at position 7 (8): Unexpected character' 

$time = new DateTime();
$time->setTimestamp( $ts );
//works fine

Any idea what's going on here? I'm using

PHP 5.3.10-1ubuntu3.2 with Suhosin-Patch (cli) (built: Jun 13 2012 17:19:58) 
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies

Upvotes: 0

Views: 357

Answers (2)

Alexander Palamarchuk
Alexander Palamarchuk

Reputation: 879

To initialize DateTime with UNIX_TIMESTAMP, use @ at the beginning:

$time = new DateTime ('@'.$this->get_start_date()); 

See compound formats in PHP manual about formats which are accepted by strtodate() and DateTime() as well.

Upvotes: 3

Daniel M
Daniel M

Reputation: 3379

Check the DateTime::__construct()

DateTime's constructor doesn't await a unix timestamp but a datetime string using the format Y-m-d H:i:s

Your second approach is just fine.

Upvotes: 0

Related Questions