From 0e646a2a4d16598023d37a96a7dfd5c606ad74b7 Mon Sep 17 00:00:00 2001 From: mark_story Date: Tue, 9 Apr 2013 21:30:20 -0400 Subject: [PATCH] Fix incorrect timestamp values when using fromString() When using fromString() on DateTime objects that were in the global timezone, an incorrect value would be returned. Fixes #3743 --- lib/Cake/Test/Case/Utility/CakeTimeTest.php | 15 ++++++++++++++- lib/Cake/Utility/CakeTime.php | 9 +++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/Cake/Test/Case/Utility/CakeTimeTest.php b/lib/Cake/Test/Case/Utility/CakeTimeTest.php index 78ab94efa..bcb17d25c 100644 --- a/lib/Cake/Test/Case/Utility/CakeTimeTest.php +++ b/lib/Cake/Test/Case/Utility/CakeTimeTest.php @@ -846,7 +846,7 @@ class CakeTimeTest extends CakeTestCase { $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); @@ -854,6 +854,7 @@ class CakeTimeTest extends CakeTestCase { $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); @@ -861,6 +862,18 @@ class CakeTimeTest extends CakeTestCase { $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 * diff --git a/lib/Cake/Utility/CakeTime.php b/lib/Cake/Utility/CakeTime.php index 95da85d84..09698d1aa 100644 --- a/lib/Cake/Utility/CakeTime.php +++ b/lib/Cake/Utility/CakeTime.php @@ -319,10 +319,15 @@ class CakeTime { 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); }