deviantintegral/null-date-time

支持空或null DateTime对象的接口和类

1.0.0 2021-02-01 11:58 UTC

This package is auto-updated.

Last update: 2024-08-29 05:07:09 UTC


README

CircleCI

composer require deviantintegral/null-date-time

此包提供装饰\DateTime的类,使其始终可以格式化为字符串,即使时间值为空或null。

PHP的\DateTime对象没有表示“空”日期的方式。尽管存在\DateTimeInterface类,但其文档明确表示它仅用于类型提示而非实现。

我们不希望调用代码在每次get调用时都要检查null返回值。DateTimeFormatInterface要求format()在底层日期未设置时返回空字符串。

构造DateTime对象时,常见的模式是

<?php

function createTime(string $time = null): \Deviantintegral\NullDateTime\DateTimeFormatInterface
{
  if (null === $time || '' === $time) {
    return new \Deviantintegral\NullDateTime\NullDateTime();
  }

  return \Deviantintegral\NullDateTime\ConcreteDateTime::fromString($time);
}

$dateTime = createTime('now');
$dateTime->format('U'); // Will return the current Unix timestamp.
if ($dateTime instanceof \Deviantintegral\NullDateTime\ConcreteDateTimeInterface) {
  $dateTime->getDateTime()->getOffset(); // Call any of the usual \DateTime methods.
}

$dateTime = createTime('');
$dateTime->format('U'); // Will return an empty string.