Skip to content

Commit

Permalink
Added Time::parseDate()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jan 18, 2015
1 parent 5197779 commit 1c933d6
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/I18n/Time.php
Expand Up @@ -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
*
Expand Down
27 changes: 27 additions & 0 deletions tests/TestCase/I18n/TimeTest.php
Expand Up @@ -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.
Expand Down

0 comments on commit 1c933d6

Please sign in to comment.