Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added function to get timezone object

  • Loading branch information...
commit d26f869455dd9027857a441484241dbcdf5c5c8f 1 parent 058d57a
@ADmad ADmad authored
Showing with 36 additions and 7 deletions.
  1. +36 −7 lib/Cake/Utility/CakeTime.php
View
43 lib/Cake/Utility/CakeTime.php
@@ -205,9 +205,7 @@ public static function convert($serverTime, $timezone) {
if (is_numeric($timezone)) {
$userOffset = $timezone * (60 * 60);
} else {
- if (!is_object($timezone)) {
- $timezone = new DateTimeZone($timezone);
- }
+ $timezone = self::timezone($timezone);
$userOffset = $timezone->getOffset(new DateTime('@' . $gmtTime));
}
$userTime = $gmtTime + $userOffset;
@@ -215,6 +213,36 @@ public static function convert($serverTime, $timezone) {
}
/**
+ * Returns a timezone object from a string or the user's timezone object
+ *
+ * @param mixed $timezone Timezone string or DateTimeZone object
+ * If null it tries to get timezone from 'Config.timezone' config var
+ * @return DateTimeZone Timezone object
+ */
+ public function timezone($timezone = null) {
+ static $tz = null;
+
+ if (is_object($timezone)) {
+ if ($tz === null || $tz->getName() !== $timezone->getName()) {
+ $tz = $timezone;
+ }
+ } else {
+ if ($timezone === null) {
+ $timezone = Configure::read('Config.timezone');
+ if ($timezone === null) {
+ $timezone = date_default_timezone_get();
+ }
+ }
+
+ if ($tz === null || $tz->getName() !== $timezone) {
+ $tz = new DateTimeZone($timezone);
+ }
+ }
+
+ return $tz;
+ }
+
+/**
* Returns server's offset from GMT in seconds.
*
* @return integer Offset
@@ -480,11 +508,12 @@ public static function toUnix($dateString, $timezone = null) {
* @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');
+ $timezone = self::timezone($timezone);
+ $time = new DateTime($dateString, $timezone);
+ $serverTimezone = date_default_timezone_get();
+ if ($serverTimezone !== $timezone->getName()) {
+ $time->setTimezone(new DateTimeZone($serverTimezone));
}
- $time = new DateTime($dateString, new DateTimeZone($timezone));
- $time->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $time->format($format);
}
Please sign in to comment.
Something went wrong with that request. Please try again.