Skip to content

Commit

Permalink
Fix incorrect timestamp values when using fromString()
Browse files Browse the repository at this point in the history
When using fromString() on DateTime objects that were in the global
timezone, an incorrect value would be returned.

Fixes #3743
  • Loading branch information
markstory committed Apr 10, 2013
1 parent 0e5b00f commit 0e646a2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
15 changes: 14 additions & 1 deletion lib/Cake/Test/Case/Utility/CakeTimeTest.php
Expand Up @@ -846,21 +846,34 @@ public function testFromStringWithDateTime() {
$date = new DateTime('+1 hour', new DateTimeZone('America/New_York'));
$result = $this->Time->fromString($date, 'UTC');
$date->setTimezone(new DateTimeZone('UTC'));
$expected = $date->format('U') + $date->getOffset();
$expected = $date->getTimestamp() + $date->getOffset();

$this->assertWithinMargin($expected, $result, 1);

date_default_timezone_set('Australia/Melbourne');

$date = new DateTime('+1 hour', new DateTimeZone('America/New_York'));
$result = $this->Time->fromString($date, 'Asia/Kuwait');

$date->setTimezone(new DateTimeZone('Asia/Kuwait'));
$expected = $date->format('U') + $date->getOffset();
$this->assertWithinMargin($expected, $result, 1);

$this->_restoreSystemTimezone();
}

/**
* Test that datetimes in the default timezone are not modified.
*
* @return void
*/
public function testFromStringWithDateTimeNoConversion() {
Configure::write('Config.timezone', date_default_timezone_get());
$date = new DateTime('2013-04-09');
$result = $this->Time->fromString($date);
$this->assertEquals($result, $date->getTimestamp());
}

/**
* test converting time specifiers using a time definition localfe file
*
Expand Down
9 changes: 7 additions & 2 deletions lib/Cake/Utility/CakeTime.php
Expand Up @@ -319,10 +319,15 @@ public static function fromString($dateString, $timezone = null) {

if (is_int($dateString) || is_numeric($dateString)) {
$date = intval($dateString);
} elseif (is_object($dateString) && $dateString instanceof DateTime) {
} elseif (
$dateString instanceof DateTime &&
$dateString->getTimezone()->getName() != date_default_timezone_get()
) {
$clone = clone $dateString;
$clone->setTimezone(new DateTimeZone(date_default_timezone_get()));
$date = (int)$clone->format('U') + $clone->getOffset();
$date = (int)$clone->getTimestamp() + $clone->getOffset();
} elseif ($dateString instanceof DateTime) {
$date = (int)$dateString->getTimeStamp();
} else {
$date = strtotime($dateString);
}
Expand Down

0 comments on commit 0e646a2

Please sign in to comment.