Commit 90baf211 authored by Karamel's avatar Karamel
Browse files

Detect some date strings with DateUtils.

parent 62cc1256
......@@ -68,6 +68,20 @@ class DateUtils
return $date;
}
/** Convert a date string to a DateTime.
* Use DateUtils::readDate instead not to bother with the input format.
* @param string $string The date. Valid format are YYYY-MM-DD
* and YYYY-MM-DD HH:mm.
* @return DateTime|false DateTime on success, false if not a valid
* date string. */
public static function readString($string) {
$date = \DateTime::createFromFormat('!Y-m-d', $string);
if ($date === false) {
$date = \DateTime::createFromFormat('Y-m-d h:i', $string);
}
return $date;
}
/** Automatically detect date format and get a DateTime. */
public static function readDate($input) {
if ($input === null) { return null; }
......@@ -77,6 +91,9 @@ class DateUtils
if ($input instanceof \DateTime) {
return $input;
}
if (is_string($input)) {
return static::readString($input);
}
return false;
}
}
......@@ -93,6 +93,17 @@ class DateUtilsTest extends TestCase {
$this->assertFalse(DateUtils::readDate($input));
}
public function testReadDateString() {
$date = DateUtils::readDate('2017-10-01');
$this->assertNotEquals(false, $date);
$this->assertEquals('2017-10-01 00:00:00',
$date->format('Y-m-d H:i:s'));
$date = DateUtils::readDate('2017-10-01 11:30');
$this->assertNotEquals(false, $date);
$this->assertEquals('2017-10-01 11:30:00',
$date->format('Y-m-d H:i:s'));
}
/** @depends testReadDateTimestamp
* @depends testReadDateDateTime */
public function testEquals() {
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment