代码之家  ›  专栏  ›  技术社区  ›  Waku-2 Cyril Gandon

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

  •  0
  • Waku-2 Cyril Gandon  · 技术社区  · 6 年前

    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 回复  |  直到 6 年前