Carbon: Construct from DateTime object

Created on 2 Nov 2014  路  2Comments  路  Source: briannesbitt/Carbon

I'm using Doctrine 2 ORM, and it maps datetime fields to instances of PHP's DateTime class (that Carbon extends, right?).

I'm looking for a way to 'upgrade' the DateTime object to a Carbon instance, without losing the timezone and other things.

I've tried

Carbon::createFromTimestamp($dateTime->getTimestamp());

It is making the date really weird.

Is there a better way to do this?

Most helpful comment

Right from the docs:

Finally, if you find yourself inheriting a DateTime instance from another library, fear not! You can create a Carbon instance via a friendly instance() function.

$dt = new \DateTime('first day of January 2008'); // <== instance from another API
$carbon = Carbon::instance($dt);
echo get_class($carbon);                               // 'Carbon\Carbon'
echo $carbon->toDateTimeString();                      // 2008-01-01 00:00:00

All 2 comments

Right from the docs:

Finally, if you find yourself inheriting a DateTime instance from another library, fear not! You can create a Carbon instance via a friendly instance() function.

$dt = new \DateTime('first day of January 2008'); // <== instance from another API
$carbon = Carbon::instance($dt);
echo get_class($carbon);                               // 'Carbon\Carbon'
echo $carbon->toDateTimeString();                      // 2008-01-01 00:00:00

Thanks! I looked through the docs but I must have missed that bit.

Was this page helpful?
0 / 5 - 0 ratings