Skip to content

Commit

Permalink
Added function to convert time from user timezone to server timezone.
Browse files Browse the repository at this point in the history
  • Loading branch information
ADmad committed Apr 21, 2012
1 parent a96de99 commit 058d57a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/Cake/Test/Case/Utility/CakeTimeTest.php
Expand Up @@ -394,6 +394,27 @@ public function testToUnix() {
$this->assertEquals(false, $this->Time->toUnix(null));
}

/**
* testToServer method
*
* @return void
*/
public function testToServer() {
$tzBackup = date_default_timezone_get();

date_default_timezone_set('UTC');
$serverTime = new DateTime('now');

$timezones = array('Europe/London', 'Europe/Brussels', 'UTC', 'America/Denver', 'America/Caracas', 'Asia/Kathmandu');
foreach ($timezones as $timezone) {
$result = $this->Time->toServer($serverTime->format('Y-m-d H:i:s'), $timezone, 'U');
$tz = new DateTimeZone($timezone);
$this->assertEquals($serverTime->format('U'), $result + $tz->getOffset($serverTime));
}

date_default_timezone_set($tzBackup);
}

/**
* testToAtom method
*
Expand Down
17 changes: 17 additions & 0 deletions lib/Cake/Utility/CakeTime.php
Expand Up @@ -471,6 +471,23 @@ public static function toUnix($dateString, $timezone = null) {
return self::fromString($dateString, $timezone);
}

/**
* Returns a formatted date in server's timezone.
*
* @param string $dateString Datetime string
* @param mixed $timezone Timezone string or DateTimeZone object
* @param string $format date format string
* @return mixed Formatted date
*/
public static function toServer($dateString, $timezone = null, $format = 'Y-m-d H:i:s') {
if ($timezone === null) {
$timezone = Configure::read('Config.timezone');
}
$time = new DateTime($dateString, new DateTimeZone($timezone));
$time->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $time->format($format);
}

/**
* Returns a date formatted for Atom RSS feeds.
*
Expand Down

0 comments on commit 058d57a

Please sign in to comment.