Carbonize
, (*1)
Carbon helper for creating new instances of Carbon from other Carbon objects,
DateTime|Immutable objects, date strings, timestamps, or null (for now
)., (*2)
Sometimes we have to work on projects that already exist or are underway, that are full of magic and inconsistent date formats.
Is this going to be a timestamp? a date string? a Carbon instance? Does it even matter as long as it's a datetime of some sort? ¯\_(ツ)_/¯, (*3)
public function doMyThing($datetime)
{
// Whatever it was, it is _now_ a NEW carbon instance
$datetime = carbonize($datetime);
// do stuff with your carbon instance
}
You can use it as either carbonize()
, carbon()
, or Carbonize\Carbonize::toCarbon()
., (*4)
Install
composer require ryanwinchester/carbonize
This does not install carbon as a dependency, so add it yourself., (*5)
Important Note: Please use Carbon 1.21 (not 1.22) until timezones are fixed. (https://github.com/briannesbitt/Carbon/issues/863), (*6)
What it does
carbonize() == Carbon::now("UTC");
$carbon = new Carbon();
carbonize($carbon) == $carbon->copy();
$dt = new DateTime();
carbonize($dt) == Carbon::instance($dt);
$dtImmutable = new DateTimeImmutable();
carbonize($dtImmutable) == Carbon::instance(new DateTime($dtImmutable->format(DateTime::ATOM)));
carbonize(1507957785) == Carbon::createFromTimestamp(1507957785, "UTC");
carbonize("1507957785") == Carbon::createFromTimestamp(1507957785, "UTC");
carbonize("2017-01-01 12:04:01") == Carbon::parse("2017-01-01 12:04:01", "UTC");
carbonize("3 months ago") == Carbon::parse("3 months ago", "UTC");
License
MIT, (*7)
Credits
-
Carbon (https://github.com/briannesbitt/Carbon)
Notes
Although Carbon is decent, use Chronos if you can. (https://github.com/cakephp/chronos), (*8)
<3 Chronos, Immutability FTW ᕙ(⇀‸↼‶)ᕗ, (*9)