I'm extending DateTime do add some useful methods and constants.
When using new to create a new object everything is fine but when using the static method createFromFormat it always returns the original DateTime object and of course none of the child methods are available.
I am using the following code to circumvent this issue. Is this the best approach?
namespace NoiseLabs\DateTime;
class DateTime extends \DateTime
{
static public function createFromFormat($format, $time)
{
$ext_dt = new self();
$ext_dt->setTimestamp(parent::createFromFormat($format, time)->getTimestamp());
return $ext_dt;
}
}
I think your solution is fine. An alternative way (just refactored a bit) is this:
public static function fromDateTime(DateTime $foo)
{
return new static($foo->format('Y-m-d H:i:s e'));
}
public static function createFromFormat($f, $t, $tz)
{
return static::fromDateTime(parent::createFromFormat($f, $t, $tz));
}
I'm not sure what the best way to implement the fromDateTime is. You could even take what you've got and put it in there. Just make sure not to lose the timezone.
Note that you could even implement __callStatic and use a bit of reflection to make it future proof.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With