From 1c933d66d82c732cc05849c1a91b21c4af668c93 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Sun, 18 Jan 2015 18:21:08 +0100 Subject: [PATCH] Added Time::parseDate() --- src/I18n/Time.php | 31 +++++++++++++++++++++++++++++++ tests/TestCase/I18n/TimeTest.php | 27 +++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/I18n/Time.php b/src/I18n/Time.php index e3ac33f462a..cf4873406a2 100644 --- a/src/I18n/Time.php +++ b/src/I18n/Time.php @@ -715,6 +715,37 @@ public static function parseDateTime($time, $format = null) return null; } + /** + * Returns a new Time object after parsing the provided $date string based on + * the passed or configured date time format. This method is locale dependent, + * Any string that is passed to this function will be intepreted as a locale + * dependent string. + * + * When no $format is provided, the `wordFormat` format will be used. + * + * If it was impossible to parse the provided time, null will be returned. + * + * Example: + * + * {{{ + * $time = Time::parseDate('10/13/2013'); + * $time = Time::parseDate('13 Oct, 2013', 'dd MMM, y'); + * $time = Time::parseDate('13 Oct, 2013', IntlDateFormatter::SHORT); + * }}} + * + * @param string $date The date string to parse. + * @param string|array|int $format Any format accepted by IntlDateFormatter. + * @return static|null + */ + public static function parseDate($date, $format = null) + { + if (is_int($format)) { + $format = [$format, -1]; + } + $format = $format ?: static::$wordFormat; + return static::parseDateTime($date, $format); + } + /** * Returns a string that should be serialized when converting this object to json * diff --git a/tests/TestCase/I18n/TimeTest.php b/tests/TestCase/I18n/TimeTest.php index 34c2fce89f3..36e10644732 100644 --- a/tests/TestCase/I18n/TimeTest.php +++ b/tests/TestCase/I18n/TimeTest.php @@ -687,6 +687,33 @@ public function testParseDateTime() { $this->assertEquals('2013-10-13 13:54', $time->format('Y-m-d H:i')); } + /** + * Tests parsing a string into a Time object based on the locale format. + * + * @return void + */ + public function testParseDate() { + $time = Time::parseDate('10/13/2013 12:54am'); + $this->assertNotNull($time); + $this->assertEquals('2013-10-13 00:00', $time->format('Y-m-d H:i')); + + $time = Time::parseDate('10/13/2013'); + $this->assertNotNull($time); + $this->assertEquals('2013-10-13 00:00', $time->format('Y-m-d H:i')); + + Time::$defaultLocale = 'fr-FR'; + $time = Time::parseDate('13 10, 2013 12:54'); + $this->assertNotNull($time); + $this->assertEquals('2013-10-13 00:00', $time->format('Y-m-d H:i')); + + $time = Time::parseDate('13 foo 10 2013 12:54'); + $this->assertNull($time); + + $time = Time::parseDate('13 Oct, 2013', 'dd MMM, y'); + $this->assertNotNull($time); + $this->assertEquals('2013-10-13 00:00', $time->format('Y-m-d H:i')); + } + /** * Custom assert to allow for variation in the version of the intl library, where * some translations contain a few extra commas.