Skip to content

Commit

Permalink
DateTime: createFromFormat() returns Nette\Utils\DateTime instance
Browse files Browse the repository at this point in the history
  • Loading branch information
redhead committed Apr 28, 2014
1 parent 6e9c27a commit a7303e8
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
23 changes: 23 additions & 0 deletions src/Utils/DateTime.php
Expand Up @@ -86,4 +86,27 @@ public function getTimestamp()
return is_float($tmp = $ts * 1) ? $ts : $tmp;
}


/**
* Returns new DateTime object formatted according to the specified format.
* @param string The format the $time parameter should be in
* @param string String representing the time
* @param string|\DateTimeZone desired timezone (default timezone is used if NULL is passed)
* @return DateTime
*/
public static function createFromFormat($format, $time, $timezone = NULL)
{
if ($timezone === NULL) {
$timezone = new \DateTimeZone(date_default_timezone_get());

} elseif (is_string($timezone)) {
$timezone = new \DateTimeZone($timezone);

} elseif (!$timezone instanceof \DateTimeZone) {
throw new Nette\InvalidArgumentException('Invalid timezone given');
}

return static::from(parent::createFromFormat($format, $time, $timezone));
}

}
27 changes: 27 additions & 0 deletions tests/Utils/DateTime.createFromFormat.phpt
@@ -0,0 +1,27 @@
<?php

/**
* Test: Nette\DateTime::createFromFormat().
*
* @author Radek Je啪d铆k
*/

use Tester\Assert,
Nette\Utils\DateTime;

require __DIR__ . '/../bootstrap.php';


date_default_timezone_set('Europe/Prague');

Assert::type( 'Nette\Utils\DateTime', DateTime::createFromFormat('Y-m-d H:i:s', '2050-08-13 11:40:00') );
Assert::type( 'Nette\Utils\DateTime', DateTime::createFromFormat('Y-m-d H:i:s', '2050-08-13 11:40:00', new DateTimeZone('Europe/Prague')) );

Assert::same( '2050-08-13 11:40:00', (string) DateTime::createFromFormat('Y-m-d H:i:s', '2050-08-13 11:40:00') );

Assert::same( 'Europe/Prague', DateTime::createFromFormat('Y', '2050')->getTimezone()->getName() );
Assert::same( 'Europe/Bratislava', DateTime::createFromFormat('Y', '2050', 'Europe/Bratislava')->getTimezone()->getName() );

Assert::error(function(){
DateTime::createFromFormat('Y-m-d H:i:s', '2050-08-13 11:40:00', 5);
}, 'Nette\InvalidArgumentException', 'Invalid timezone given' );
2 changes: 1 addition & 1 deletion tests/Utils/DateTime.from.phpt
@@ -1,7 +1,7 @@
<?php

/**
* Test: Nette\Utils\DateTime test.
* Test: Nette\Utils\DateTime::from().
*
* @author David Grudl
*/
Expand Down

0 comments on commit a7303e8

Please sign in to comment.