php检查为DateTime类提供的格式字符串的有效性

时间:2018-08-24 07:10:47

标签: php datetime

EventTime是一个简单的类,可以返回事件的格式化时间戳。这是我的EventTime测试用例类

class EventTimeTest extends TestCase
{

    private $eventTime;
    private $dateTime;

    public function setUp()
    {
        parent::setUp();
        $this->dateTime = new \DateTime('now', new \DateTimeZone('Asia/Tokyo'));
        $this->eventTime = new EventTime($this->dateTime);
    }



    public function test_event_time_returns_a_valid_timestamp_when_format_is_given()
    {
        $this->assertEquals($this->dateTime->format("Y-m-d H:i:s.u"), $this->eventTime->time("Y-m-d H:i:s.u"), "Event time should be a valid time");

    }

    public function test_event_time_throws_exception_when_format_is_not_valid()
    {
        $this->assertEquals($this->dateTime->format("Y-m-d H:i:s.u"), $this->eventTime->time("some completely invalid format string provided with funny characters & smileys"), "Event time should be a valid time");

    }

}

现在这是我上面正在测试的实际EventTime类

class EventTime implements EventTimeInterface
{
    private $timeStamp;

    public function __construct(\DateTime $time)
    {
        $this->timeStamp = $time;
    }

    public function time(string $format="Y-m-d H:i:s.u"): string
    {
        return $this->timeStamp->format($format);
    }
}

我无法弄清楚如何处理无效的格式字符串。如果是emty字符串,则很容易检查,但是'11'或'¥¥¥¥¥¥¥¥¥¥¥¥¥'之类的字符串呢?在这种情况下,php是否具有一些内置机制来引发异常?

0 个答案:

没有答案