2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 require_once 'include/SugarDateTime.php';
42 * New Time & Date handling class
45 * - to_db_time() requires either full datetime or time, won't work with just date
46 * The reason is that it's not possible to know if short string has only date or only time,
47 * and it makes more sense to assume time for the time conversion function.
51 const DB_DATE_FORMAT = 'Y-m-d';
52 const DB_TIME_FORMAT = 'H:i:s';
53 // little optimization
54 const DB_DATETIME_FORMAT = 'Y-m-d H:i:s';
55 const RFC2616_FORMAT = 'D, d M Y H:i:s \G\M\T';
57 const SECONDS_IN_A_DAY = 86400;
59 // Standard DB date/time formats
60 // they are constant, vars are for compatibility
61 public $dbDayFormat = self::DB_DATE_FORMAT;
62 public $dbTimeFormat = self::DB_TIME_FORMAT;
65 * Regexp for matching format elements
68 protected static $format_to_regexp = array(
87 * Relation between date() and strftime() formats
90 public static $format_to_str = array(
115 * GMT timezone object
119 protected static $gmtTimezone;
139 protected $current_user_id;
144 protected $current_user_tz;
147 * Separator for current user time format
151 protected $time_separator;
154 * Always consider user TZ to be GMT and date format DB format - for SOAP etc.
158 protected $always_db = false;
161 * Global instance of TimeDate
164 protected static $timedate;
167 * Allow returning cached now() value
168 * If false, new system time is checked each time now() is required
169 * If true, same value is returned for whole request.
170 * Also, current user's timezone is cached.
173 public $allow_cache = true;
176 * Create TimeDate handler
177 * @param User $user User to work with, default if current user
179 public function __construct(User $user = null)
181 if (self::$gmtTimezone == null) {
182 self::$gmtTimezone = new DateTimeZone("UTC");
184 $this->now = new SugarDateTime();
185 $this->tzGMT($this->now);
190 * Set flag specifying we should always use DB format
194 public function setAlwaysDb($flag = true)
196 $this->always_db = $flag;
202 * Get "always use DB format" flag
205 public function isAlwaysDb()
207 return !empty($GLOBALS['disable_date_format']) || $this->always_db;
211 * Get TimeDate instance
214 public static function getInstance()
216 if(empty(self::$timedate)) {
217 if(ini_get('date.timezone') == '') {
218 // Remove warning about default timezone
219 date_default_timezone_set(@date('e'));
221 $tz = self::guessTimezone();
222 } catch(Exception $e) {
223 $tz = "UTC"; // guess failed, switch to UTC
225 if(isset($GLOBALS['log'])) {
226 $GLOBALS['log']->fatal("Configuration variable date.timezone is not set, guessed timezone $tz. Please set date.timezone=\"$tz\" in php.ini!");
228 date_default_timezone_set($tz);
230 self::$timedate = new self;
232 return self::$timedate;
236 * Set current user for this object
238 * @param User $user User object, default is current user
241 public function setUser(User $user = null)
249 * Figure out what the required user is
251 * The order is: supplied parameter, TimeDate's user, global current user
253 * @param User $user User object, default is current user
257 protected function _getUser(User $user = null)
263 $user = $GLOBALS['current_user'];
269 * Get timezone for the specified user
271 * @param User $user User object, default is current user
272 * @return DateTimeZone
274 protected function _getUserTZ(User $user = null)
276 $user = $this->_getUser($user);
277 if (empty($user) || $this->isAlwaysDb()) {
278 return self::$gmtTimezone;
281 if ($this->allow_cache && $user->id == $this->current_user_id && ! empty($this->current_user_tz)) {
282 // current user is cached
283 return $this->current_user_tz;
286 $usertimezone = $user->getPreference('timezone');
287 if(empty($usertimezone)) {
288 return self::$gmtTimezone;
291 $tz = new DateTimeZone($usertimezone);
292 } catch (Exception $e) {
293 $GLOBALS['log']->fatal('Unknown timezone: ' . $usertimezone);
294 return self::$gmtTimezone;
297 if (empty($this->current_user_id)) {
298 $this->current_user_id = $user->id;
299 $this->current_user_tz = $tz;
306 * Clears all cached data regarding current user
308 public function clearCache()
310 $this->current_user_id = null;
311 $this->current_user_tz = null;
312 $this->time_separator = null;
313 $this->now = new SugarDateTime();
317 * Get user date format.
320 * @param User $user user object, current user if not specified
323 public function get_date_format(User $user = null)
325 $user = $this->_getUser($user);
327 if (empty($user) || $this->isAlwaysDb()) {
328 return self::DB_DATE_FORMAT;
331 $datef = $user->getPreference('datef');
332 if(empty($datef) && isset($GLOBALS['current_user']) && $GLOBALS['current_user'] !== $user) {
333 // if we got another user and it has no date format, try current user
334 $datef = $GLOBALS['current_user']->getPreference('datef');
337 $datef = $GLOBALS['sugar_config']['default_date_format'];
347 * Get user time format.
350 * @param User $user user object, current user if not specified
353 public function get_time_format(/*User*/ $user = null)
355 if(is_bool($user) || func_num_args() > 1) {
356 // BC dance - old signature was boolean, User
357 $GLOBALS['log']->fatal('TimeDate::get_time_format(): Deprecated API used, please update you code - get_time_format() now has one argument of type User');
358 if(func_num_args() > 1) {
359 $user = func_get_arg(1);
364 $user = $this->_getUser($user);
366 if (empty($user) || $this->isAlwaysDb()) {
367 return self::DB_TIME_FORMAT;
370 $timef = $user->getPreference('timef');
371 if(empty($timef) && isset($GLOBALS['current_user']) && $GLOBALS['current_user'] !== $user) {
372 // if we got another user and it has no time format, try current user
373 $timef = $GLOBALS['current_user']->getPreference('$timef');
376 $timef = $GLOBALS['sugar_config']['default_time_format'];
385 * Get user datetime format.
388 * @param User $user user object, current user if not specified
391 public function get_date_time_format($user = null)
393 // BC fix - had (bool, user) signature before
394 if(!($user instanceof User)) {
395 if(func_num_args() > 1) {
396 $user = func_get_arg(1);
397 if(!($user instanceof User)) {
404 return $this->merge_date_time($this->get_date_format($user), $this->get_time_format($user));
409 * Get user's first day of week setting.
411 * @param User $user user object, current user if not specified
412 * @return int Day, 0 = Sunday, 1 = Monday, etc...
414 public function get_first_day_of_week(User $user = null)
416 $user = $this->_getUser($user);
421 $fdow = $user->getPreference('fdow');
431 * Make one datetime string from date string and time string
433 * @param string $date
434 * @param string $time
435 * @return string New datetime string
437 function merge_date_time($date, $time)
439 return $date . ' ' . $time;
443 * Split datetime string into date & time
445 * @param string $datetime
448 function split_date_time($datetime)
450 return explode(' ', $datetime, 2);
455 * Get user date format in Javascript form
458 function get_cal_date_format()
460 return str_replace(array_keys(self::$format_to_str), array_values(self::$format_to_str), $this->get_date_format());
464 * Get user time format in Javascript form
467 function get_cal_time_format()
469 return str_replace(array_keys(self::$format_to_str), array_values(self::$format_to_str), $this->get_time_format());
473 * Get user date&time format in Javascript form
476 function get_cal_date_time_format()
478 return str_replace(array_keys(self::$format_to_str), array_values(self::$format_to_str), $this->get_date_time_format());
482 * Verify if the date string conforms to a format
484 * @param string $date
485 * @param string $format Format to check
488 * @return bool Is the date ok?
490 public function check_matching_format($date, $format)
493 $dt = SugarDateTime::createFromFormat($format, $date);
494 if (!is_object($dt)) {
497 } catch (Exception $e) {
504 * Format DateTime object as DB datetime
506 * @param DateTime $date
509 public function asDb(DateTime $date)
511 $date->setTimezone(self::$gmtTimezone);
512 return $date->format($this->get_db_date_time_format());
516 * Format date as DB-formatted field type
517 * @param DateTime $date
518 * @param string $type Field type - date, time, datetime[combo]
519 * @return string Formatted date
521 public function asDbType(DateTime $date, $type)
525 return $this->asDbDate($date);
528 return $this->asDbtime($date);
531 case 'datetimecombo':
533 return $this->asDb($date);
538 * Format DateTime object as user datetime
540 * @param DateTime $date
544 public function asUser(DateTime $date, User $user = null)
546 $this->tzUser($date, $user);
547 return $date->format($this->get_date_time_format($user));
551 * Format date as user-formatted field type
552 * @param DateTime $date
553 * @param string $type Field type - date, time, datetime[combo]
557 public function asUserType(DateTime $date, $type, User $user = null)
561 return $this->asUserDate($date, true, $user);
564 return $this->asUserTime($date, true, $user);
567 case 'datetimecombo':
569 return $this->asUser($date, $user);
574 * Produce timestamp offset by user's timezone
576 * So if somebody converts it to format assuming GMT, it would actually display user's time.
577 * This is used by Javascript.
579 * @param DateTime $date
583 public function asUserTs(DateTime $date, User $user = null)
585 return $date->format('U')+$this->_getUserTZ($user)->getOffset($date);
589 * Format DateTime object as DB date
590 * Note: by default does not convert TZ!
591 * @param DateTime $date
592 * @param boolean $tz Perform TZ conversion?
595 public function asDbDate(DateTime $date, $tz = false)
597 if($tz) $date->setTimezone(self::$gmtTimezone);
598 return $date->format($this->get_db_date_format());
602 * Format DateTime object as user date
603 * Note: by default does not convert TZ!
604 * @param DateTime $date
605 * @param boolean $tz Perform TZ conversion?
609 public function asUserDate(DateTime $date, $tz = false, User $user = null)
611 if($tz) $this->tzUser($date, $user);
612 return $date->format($this->get_date_format($user));
616 * Format DateTime object as DB time
618 * @param DateTime $date
621 public function asDbTime(DateTime $date)
623 $date->setTimezone(self::$gmtTimezone);
624 return $date->format($this->get_db_time_format());
628 * Format DateTime object as user time
630 * @param DateTime $date
634 public function asUserTime(DateTime $date, User $user = null)
636 $this->tzUser($date, $user);
637 return $date->format($this->get_time_format($user));
641 * Get DateTime from DB datetime string
643 * @param string $date
644 * @return SugarDateTime
646 public function fromDb($date)
649 return SugarDateTime::createFromFormat(self::DB_DATETIME_FORMAT, $date, self::$gmtTimezone);
650 } catch (Exception $e) {
651 $GLOBALS['log']->error("fromDb: Conversion of $date from DB format failed: {$e->getMessage()}");
657 * Create a date from a certain type of field in DB format
658 * The types are: date, time, datatime[combo]
659 * @param string $date the datetime string
660 * @param string $type string type
661 * @return SugarDateTime
663 public function fromDbType($date, $type)
667 return $this->fromDbDate($date);
670 return $this->fromDbFormat($date, self::DB_TIME_FORMAT);
673 case 'datetimecombo':
675 return $this->fromDb($date);
680 * Get DateTime from DB date string
682 * @param string $date
683 * @return SugarDateTime
685 public function fromDbDate($date)
688 return SugarDateTime::createFromFormat(self::DB_DATE_FORMAT, $date, self::$gmtTimezone);
689 } catch (Exception $e) {
690 $GLOBALS['log']->error("fromDbDate: Conversion of $date from DB format failed: {$e->getMessage()}");
696 * Get DateTime from DB datetime string using non-standard format
698 * Non-standard format usually would be only date, only time, etc.
700 * @param string $date
701 * @param string $format format to accept
702 * @return SugarDateTime
704 public function fromDbFormat($date, $format)
707 return SugarDateTime::createFromFormat($format, $date, self::$gmtTimezone);
708 } catch (Exception $e) {
709 $GLOBALS['log']->error("fromDbFormat: Conversion of $date from DB format $format failed: {$e->getMessage()}");
715 * Get DateTime from user datetime string
717 * @param string $date
719 * @return SugarDateTime
721 public function fromUser($date, User $user = null)
725 $res = SugarDateTime::createFromFormat($this->get_date_time_format($user), $date, $this->_getUserTZ($user));
726 } catch (Exception $e) {
727 $GLOBALS['log']->error("fromUser: Conversion of $date exception: {$e->getMessage()}");
729 if(!($res instanceof DateTime)) {
730 $uf = $this->get_date_time_format($user);
731 $GLOBALS['log']->error("fromUser: Conversion of $date from user format $uf failed");
738 * Create a date from a certain type of field in user format
739 * The types are: date, time, datatime[combo]
740 * @param string $date the datetime string
741 * @param string $type string type
743 * @return SugarDateTime
745 public function fromUserType($date, $type, $user = null)
749 return $this->fromUserDate($date, $user);
752 return $this->fromUserTime($date, $user);
755 case 'datetimecombo':
757 return $this->fromUser($date, $user);
762 * Get DateTime from user time string
764 * @param string $date
766 * @return SugarDateTime
768 public function fromUserTime($date, User $user = null)
771 return SugarDateTime::createFromFormat($this->get_time_format($user), $date, $this->_getUserTZ($user));
772 } catch (Exception $e) {
773 $uf = $this->get_time_format($user);
774 $GLOBALS['log']->error("fromUserTime: Conversion of $date from user format $uf failed: {$e->getMessage()}");
780 * Get DateTime from user date string
781 * Usually for calendar-related functions like holidays
782 * Note: by default does not convert tz!
783 * @param string $date
784 * @param bool $convert_tz perform TZ converson?
786 * @return SugarDateTime
788 public function fromUserDate($date, $convert_tz = false, User $user = null)
791 return SugarDateTime::createFromFormat($this->get_date_format($user), $date, $convert_tz?$this->_getUserTZ($user):self::$gmtTimezone);
792 } catch (Exception $e) {
793 $uf = $this->get_date_format($user);
794 $GLOBALS['log']->error("fromUserDate: Conversion of $date from user format $uf failed: {$e->getMessage()}");
800 * Create a date object from any string
802 * Same formats accepted as for DateTime ctor
804 * @param string $date
806 * @return SugarDateTime
808 public function fromString($date, User $user = null)
811 return new SugarDateTime($date, $this->_getUserTZ($user));
812 } catch (Exception $e) {
813 $GLOBALS['log']->error("fromString: Conversion of $date from string failed: {$e->getMessage()}");
819 * Create DateTime from timestamp
821 * @param interger|string $ts
822 * @return SugarDateTime
824 public function fromTimestamp($ts)
826 return new SugarDateTime("@$ts");
830 * Convert DateTime to GMT timezone
831 * @param DateTime $date
834 public function tzGMT(DateTime $date)
836 return $date->setTimezone(self::$gmtTimezone);
840 * Convert DateTime to user timezone
841 * @param DateTime $date
845 public function tzUser(DateTime $date, User $user = null)
847 return $date->setTimezone($this->_getUserTZ($user));
851 * Get string defining midnight in current user's format
852 * @param string $format Time format to use
855 protected function _get_midnight($format = null)
857 $zero = new DateTime("@0", self::$gmtTimezone);
858 return $zero->format($format?$format:$this->get_time_format());
863 * Basic conversion function
865 * Converts between two string dates in different formats and timezones
867 * @param string $date
868 * @param string $fromFormat
869 * @param DateTimeZone $fromTZ
870 * @param string $toFormat
871 * @param DateTimeZone|null $toTZ
872 * @param bool $expand If string lacks time, expand it to include time
875 protected function _convert($date, $fromFormat, $fromTZ, $toFormat, $toTZ, $expand = false)
882 if ($expand && strlen($date) <= 10) {
883 $date = $this->expandDate($date, $fromFormat);
885 $phpdate = SugarDateTime::createFromFormat($fromFormat, $date, $fromTZ);
886 if ($phpdate == false) {
887 $GLOBALS['log']->error("convert: Conversion of $date from $fromFormat to $toFormat failed");
890 if ($fromTZ !== $toTZ && $toTZ != null) {
891 $phpdate->setTimeZone($toTZ);
893 return $phpdate->format($toFormat);
894 } catch (Exception $e) {
895 $GLOBALS['log']->error("Conversion of $date from $fromFormat to $toFormat failed: {$e->getMessage()}");
901 * Convert DB datetime to local datetime
903 * TZ conversion is controlled by parameter
905 * @param string $date Original date in DB format
906 * @param bool $meridiem Ignored for BC
907 * @param bool $convert_tz Perform TZ conversion?
908 * @param User $user User owning the conversion formats
909 * @return string Date in display format
911 function to_display_date_time($date, $meridiem = true, $convert_tz = true, $user = null)
913 return $this->_convert($date,
914 self::DB_DATETIME_FORMAT, self::$gmtTimezone, $this->get_date_time_format($user),
915 $convert_tz ? $this->_getUserTZ($user) : self::$gmtTimezone, true);
919 * Converts DB time string to local time string
921 * TZ conversion depends on parameter
923 * @param string $date Time in DB format
924 * @param bool $meridiem
925 * @param bool $convert_tz Perform TZ conversion?
926 * @return string Time in user-defined format
928 public function to_display_time($date, $meridiem = true, $convert_tz = true)
930 if($convert_tz && strpos($date, ' ') === false) {
931 // we need TZ adjustment but have no date, assume today
932 $date = $this->expandTime($date, self::DB_DATETIME_FORMAT, self::$gmtTimezone);
934 return $this->_convert($date,
935 $convert_tz ? self::DB_DATETIME_FORMAT : self::DB_TIME_FORMAT, self::$gmtTimezone,
936 $this->get_time_format(), $convert_tz ? $this->_getUserTZ() : self::$gmtTimezone);
940 * Splits time in given format into components
942 * Components: h, m, s, a (am/pm) if format requires it
943 * If format has am/pm, hour is 12-based, otherwise 24-based
945 * @param string $date
946 * @param string $format
949 public function splitTime($date, $format)
951 if (! ($date instanceof DateTime)) {
952 $date = SugarDateTime::createFromFormat($format, $date);
954 $ampm = strpbrk($format, 'aA');
956 "h" => ($ampm == false) ? $date->format("H") : $date->format("h"),
957 'm' => $date->format("i"),
958 's' => $date->format("s")
961 $datearr['a'] = ($ampm{0} == 'a') ? $date->format("a") : $date->format("A");
967 * Converts DB date string to local date string
969 * TZ conversion depens on parameter
971 * @param string $date Date in DB format
972 * @param bool $convert_tz Perform TZ conversion?
973 * @return string Date in user-defined format
975 public function to_display_date($date, $convert_tz = true)
977 return $this->_convert($date,
978 self::DB_DATETIME_FORMAT, self::$gmtTimezone,
979 $this->get_date_format(), $convert_tz ? $this->_getUserTZ() : self::$gmtTimezone, true);
983 * Convert date from format to format
985 * No TZ conversion is performed!
987 * @param string $date
988 * @param string $from Source format
989 * @param string $to Destination format
990 * @return string Converted date
992 function to_display($date, $from, $to)
994 return $this->_convert($date, $from, self::$gmtTimezone, $to, self::$gmtTimezone);
998 * Get DB datetime format
1001 public function get_db_date_time_format()
1003 return self::DB_DATETIME_FORMAT;
1007 * Get DB date format
1010 public function get_db_date_format()
1012 return self::DB_DATE_FORMAT;
1016 * Get DB time format
1019 public function get_db_time_format()
1021 return self::DB_TIME_FORMAT;
1025 * Convert date from local datetime to GMT-based DB datetime
1027 * Includes TZ conversion.
1029 * @param string $date
1030 * @return string Datetime in DB format
1032 public function to_db($date)
1034 return $this->_convert($date,
1035 $this->get_date_time_format(), $this->_getUserTZ(),
1036 $this->get_db_date_time_format(), self::$gmtTimezone,
1041 * Convert local datetime to DB date
1043 * TZ conversion depends on parameter. If false, only format conversion is performed.
1045 * @param string $date Local date
1046 * @param bool $convert_tz Should time and TZ be taken into account?
1047 * @return string Date in DB format
1049 public function to_db_date($date, $convert_tz = true)
1051 return $this->_convert($date,
1052 $this->get_date_time_format(), $convert_tz ? $this->_getUserTZ() : self::$gmtTimezone,
1053 self::DB_DATE_FORMAT, self::$gmtTimezone, true);
1057 * Convert local datetime to DB time
1059 * TZ conversion depends on parameter. If false, only format conversion is performed.
1061 * @param string $date Local date
1062 * @param bool $convert_tz Should time and TZ be taken into account?
1063 * @return string Time in DB format
1065 public function to_db_time($date, $convert_tz = true)
1067 $format = $this->get_date_time_format();
1068 $tz = $convert_tz ? $this->_getUserTZ() : self::$gmtTimezone;
1069 if($convert_tz && strpos($date, ' ') === false) {
1070 // we need TZ adjustment but have short string, expand it to full one
1071 // FIXME: if the string is short, should we assume date or time?
1072 $date = $this->expandTime($date, $format, $tz);
1074 return $this->_convert($date,
1075 $convert_tz ? $format : $this->get_time_format(),
1077 self::DB_TIME_FORMAT, self::$gmtTimezone);
1081 * Takes a Date & Time value in local format and converts them to DB format
1084 * @param string $date
1085 * @param string $time
1086 * @return array Date & time in DB format
1088 public function to_db_date_time($date, $time)
1091 $phpdate = SugarDateTime::createFromFormat($this->get_date_time_format(),
1092 $this->merge_date_time($date, $time), self::$gmtTimezone);
1093 if ($phpdate == false) {
1094 return array('', '');
1096 return array($this->asDbDate($phpdate), $this->asDbTime($phpdate));
1097 } catch (Exception $e) {
1098 $GLOBALS['log']->error("Conversion of $date,$time failed");
1099 return array('', '');
1104 * Return current time in DB format
1107 public function nowDb()
1109 if(!$this->allow_cache) {
1110 $nowGMT = $this->getNow();
1112 $nowGMT = $this->now;
1114 return $this->asDb($nowGMT);
1118 * Return current date in DB format
1121 public function nowDbDate()
1123 if(!$this->allow_cache) {
1124 $nowGMT = $this->getNow();
1126 $nowGMT = $this->now;
1128 return $this->asDbDate($nowGMT, true);
1132 * Get 'now' DateTime object
1133 * @param bool $userTz return in user timezone?
1134 * @return SugarDateTime
1136 public function getNow($userTz = false)
1138 if(!$this->allow_cache) {
1139 return new SugarDateTime("now", $userTz?$this->_getUserTz():self::$gmtTimezone);
1141 // TODO: should we return clone?
1142 $now = clone $this->now;
1144 return $this->tzUser($now);
1151 * For testability - predictable time value
1152 * @param DateTime $now
1153 * @return TimeDate $this
1155 public function setNow($now)
1162 * Return current datetime in local format
1165 public function now()
1167 return $this->asUser($this->getNow());
1171 * Return current date in User format
1174 public function nowDate()
1176 return $this->asUserDate($this->getNow());
1180 * Get user format's time separator
1183 public function timeSeparator()
1185 if (empty($this->time_separator)) {
1186 $this->time_separator = $this->timeSeparatorFormat($this->get_time_format());
1188 return $this->time_separator;
1192 * Find out format's time separator
1193 * @param string $timeformat Time format
1196 public function timeSeparatorFormat($timeformat)
1198 $date = $this->_convert("00:11:22", self::DB_TIME_FORMAT, null, $timeformat, null);
1199 if (preg_match('/\d+(.+?)11/', $date, $matches)) {
1208 * Returns start and end of a certain local date in GMT
1209 * Example: for May 19 in PDT start would be 2010-05-19 07:00:00, end would be 2010-05-20 06:59:59
1210 * @param string|DateTime $date Date in any suitable format
1212 * @return array Start & end date in start, startdate, starttime, end, enddate, endtime
1214 public function getDayStartEndGMT($date, User $user = null)
1216 if ($date instanceof DateTime) {
1218 $min->setTimezone($this->_getUserTZ($user));
1220 $max->setTimezone($this->_getUserTZ($user));
1222 $min = new DateTime($date, $this->_getUserTZ($user));
1223 $max = new DateTime($date, $this->_getUserTZ($user));
1225 $min->setTime(0, 0);
1226 $max->setTime(23, 59, 59);
1228 $min->setTimezone(self::$gmtTimezone);
1229 $max->setTimezone(self::$gmtTimezone);
1231 $result['start'] = $this->asDb($min);
1232 $result['startdate'] = $this->asDbDate($min);
1233 $result['starttime'] = $this->asDbTime($min);
1234 $result['end'] = $this->asDb($max);
1235 $result['enddate'] = $this->asDbDate($max);
1236 $result['endtime'] = $this->asDbtime($max);
1242 * Expand date format by adding midnight to it
1243 * Note: date is assumed to be in target format already
1244 * @param string $date
1245 * @param string $format Target format
1248 public function expandDate($date, $format)
1250 $formats = $this->split_date_time($format);
1251 if(isset($formats[1])) {
1252 return $this->merge_date_time($date, $this->_get_midnight($formats[1]));
1258 * Expand time format by adding today to it
1259 * Note: time is assumed to be in target format already
1260 * @param string $date
1261 * @param string $format Target format
1262 * @param DateTimeZone $tz
1265 public function expandTime($date, $format, $tz)
1267 $formats = $this->split_date_time($format);
1268 if(isset($formats[1])) {
1269 $now = clone $this->getNow();
1270 $now->setTimezone($tz);
1271 return $this->merge_date_time($now->format($formats[0]), $date);
1277 * Get midnight (start of the day) in local time format
1279 * @return Time string
1281 function get_default_midnight()
1283 return $this->_get_midnight($this->get_time_format());
1287 * Get the name of the timezone for the user
1288 * @param User $user User, default - current user
1291 public static function userTimezone(User $user = null)
1293 $user = self::getInstance()->_getUser($user);
1297 $tz = self::getInstance()->_getUserTZ($user);
1299 return $tz->getName();
1305 * Guess the timezone for the current user
1306 * @param int $userOffset Offset from GMT in minutes
1309 public static function guessTimezone($userOffset = 0)
1311 if(!is_numeric($userOffset)) {
1314 $defaultZones= array(
1315 'America/Anchorage', 'America/Los_Angeles', 'America/Phoenix', 'America/Chicago',
1316 'America/New_York', 'America/Argentina/Buenos_Aires', 'America/Montevideo',
1317 'Europe/London', 'Europe/Amsterdam', 'Europe/Athens', 'Europe/Moscow',
1318 'Asia/Tbilisi', 'Asia/Omsk', 'Asia/Jakarta', 'Asia/Hong_Kong',
1319 'Asia/Tokyo', 'Pacific/Guam', 'Australia/Sydney', 'Australia/Perth',
1322 $now = new DateTime();
1323 $tzlist = timezone_identifiers_list();
1324 if($userOffset == 0) {
1325 $gmtOffset = date('Z');
1327 if(in_array($nowtz, $tzlist)) {
1328 array_unshift($defaultZones, $nowtz);
1330 $nowtz = timezone_name_from_abbr(date('T'), $gmtOffset, date('I'));
1331 if(in_array($nowtz, $tzlist)) {
1332 array_unshift($defaultZones, $nowtz);
1336 $gmtOffset = $userOffset * 60;
1338 foreach($defaultZones as $zoneName) {
1339 $tz = new DateTimeZone($zoneName);
1340 if($tz->getOffset($now) == $gmtOffset) {
1341 return $tz->getName();
1345 foreach($tzlist as $zoneName) {
1346 $tz = new DateTimeZone($zoneName);
1347 if($tz->getOffset($now) == $gmtOffset) {
1348 return $tz->getName();
1355 * Get the description of the user timezone for specific date
1357 * We need the date because it can be DST or non-DST
1358 * Note it's different from TZ name in tzName() that relates to current date
1359 * @param DateTime $date Current date
1360 * @param User $user User, default - current user
1363 public static function userTimezoneSuffix(DateTime $date, User $user = null)
1365 $user = self::getInstance()->_getUser($user);
1369 self::getInstance()->tzUser($date, $user);
1370 return $date->format('T(P)');
1374 * Get display name for a certain timezone
1375 * Note: it uses current date for GMT offset, so it may be not suitable for displaying generic dates
1376 * @param string|DateTimeZone $name TZ name
1379 public static function tzName($name)
1384 if($name instanceof DateTimeZone) {
1387 $tz = timezone_open($name);
1392 $now = new DateTime("now", $tz);
1393 $off = $now->getOffset();
1394 $translated = translate('timezone_dom','',$name);
1395 if(is_string($translated) && !empty($translated)) {
1396 $name = $translated;
1398 return sprintf("%s (GMT%+2d:%02d)%s", str_replace('_',' ', $name), $off/3600, (abs($off)/60)%60, "");//$now->format('I')==1?"(+DST)":"");
1403 * Timezone sorting helper
1410 public static function _sortTz($a, $b)
1412 if($a[0] == $b[0]) {
1413 return strcmp($a[1], $b[1]);
1415 return $a[0]<$b[0]?-1:1;
1420 * Get list of all timezones in the system
1423 public static function getTimezoneList()
1425 $now = new DateTime();
1426 $res_zones = $zones = array();
1427 foreach(timezone_identifiers_list() as $zoneName) {
1428 $tz = new DateTimeZone($zoneName);
1429 $zones[$zoneName] = array($tz->getOffset($now), self::tzName($zoneName));
1431 uasort($zones, array('TimeDate', '_sortTz'));
1432 foreach($zones as $name => $zonedef) {
1433 $res_zones[$name] = $zonedef[1];
1439 * Print timestamp in RFC2616 format:
1440 * @param int|null $ts Null means current ts
1443 public static function httpTime($ts = null)
1448 return gmdate(self::RFC2616_FORMAT, $ts);
1452 * Create datetime object from calendar array
1453 * @param array $time
1454 * @return SugarDateTime
1456 public function fromTimeArray($time)
1458 if (! isset( $time) || count($time) == 0 )
1460 return $this->nowDb();
1462 elseif ( isset( $time['ts']))
1464 return $this->fromTimestamp($time['ts']);
1466 elseif ( isset( $time['date_str']))
1468 return $this->fromDb($time['date_str']);
1475 $now = $this->getNow(true);
1477 $month = $now->month;
1479 if (isset($time['sec']))
1481 $sec = $time['sec'];
1483 if (isset($time['min']))
1485 $min = $time['min'];
1487 if (isset($time['hour']))
1489 $hour = $time['hour'];
1491 if (isset($time['day']))
1493 $day = $time['day'];
1495 if (isset($time['month']))
1497 $month = $time['month'];
1499 if (isset($time['year']) && $time['year'] >= 1970)
1501 $year = $time['year'];
1503 return $now->setDate($year, $month, $day)->setTime($hour, $min, $sec)->setTimeZone(self::$gmtTimezone);
1509 * Returns the date portion of a datetime string
1511 * @param string $datetime
1514 public function getDatePart($datetime)
1516 list($date, $time) = $this->split_date_time($datetime);
1521 * Returns the time portion of a datetime string
1523 * @param string $datetime
1526 public function getTimePart($datetime)
1528 list($date, $time) = $this->split_date_time($datetime);
1533 * Returns the offset from user's timezone to GMT
1535 * @param DateTime $time When the offset is taken, default is now
1536 * @return int Offset in minutes
1538 public function getUserUTCOffset(User $user = null, DateTime $time = null)
1543 return $this->_getUserTZ($user)->getOffset($time) / 60;
1547 * Create regexp from datetime format
1548 * @param string $format
1549 * @return string Regular expression string
1551 public static function get_regular_expression($format)
1554 $regPositions = array();
1555 $ignoreNextChar = false;
1557 foreach (str_split($format) as $char) {
1558 if (! $ignoreNextChar && isset(self::$format_to_regexp[$char])) {
1559 $newFormat .= '(' . self::$format_to_regexp[$char] . ')';
1560 $regPositions[$char] = $count;
1563 $ignoreNextChar = false;
1564 $newFormat .= $char;
1567 if ($char == "\\") {
1568 $ignoreNextChar = true;
1572 return array('format' => $newFormat, 'positions' => $regPositions);
1575 // format - date expression ('' means now) for start and end of the range
1576 protected $date_expressions = array(
1577 'yesterday' => array("-1 day", "-1 day"),
1578 'today' => array("", ""),
1579 'tomorrow' => array("+1 day", "+1 day"),
1580 'last_7_days' => array("-6 days", ""),
1581 'next_7_days' => array("", "+6 days"),
1582 'last_30_days' => array("-29 days", ""),
1583 'next_30_days' => array("", "+29 days"),
1587 * Parse date template
1589 * @param string $template Date expression
1590 * @param bool $daystart Do we want start or end of the day?
1592 * @return SugarDateTime
1594 protected function parseFromTemplate($template, $daystart, User $user = null)
1596 $now = $this->tzUser($this->getNow(), $user);
1597 if(!empty($template)) {
1598 $now->modify($template);
1601 return $now->get_day_begin();
1603 return $now->get_day_end();
1608 * Get month-long range mdiff months from now
1614 protected function diffMon($mdiff, User $user = null)
1616 $now = $this->tzUser($this->getNow(), $user);
1617 $now->setDate($now->year, $now->month+$mdiff, 1);
1618 $start = $now->get_day_begin();
1619 $end = $now->setDate($now->year, $now->month, $now->days_in_month)->setTime(23, 59, 59);
1620 return array($start, $end);
1624 * Get year-long range ydiff years from now
1630 protected function diffYear($ydiff, User $user = null)
1632 $now = $this->tzUser($this->getNow(), $user);
1633 $now->setDate($now->year+$ydiff, 1, 1);
1634 $start = $now->get_day_begin();
1635 $end = $now->setDate($now->year, 12, 31)->setTime(23, 59, 59);
1636 return array($start, $end);
1640 * Parse date range expression
1641 * Returns beginning and end of the range as a date
1642 * @param string $range
1644 * @return array of two Date objects, start & end
1646 public function parseDateRange($range, User $user = null)
1648 if(isset($this->date_expressions[$range])) {
1649 return array($this->parseFromTemplate($this->date_expressions[$range][0], true, $user),
1650 $this->parseFromTemplate($this->date_expressions[$range][1], false, $user)
1655 return $this->diffMon(1, $user);
1657 return $this->diffMon(-1, $user);
1659 return $this->diffMon(0, $user);
1661 return $this->diffYear(-1, $user);
1663 return $this->diffYear(0, $user);
1665 return $this->diffYear(1, $user);
1671 /********************* OLD functions, should not be used publicly anymore ****************/
1673 * Merge time without am/pm with am/pm string
1674 * @TODO find better way to do this!
1675 * @deprecated for public use
1676 * @param string $date
1677 * @param string $format User time format
1678 * @param string $mer
1681 function merge_time_meridiem($date, $format, $mer)
1683 $date = trim($date);
1687 $fakeMerFormat = str_replace(array('a', 'A'), array('@~@', '@~@'), $format);
1688 $noMerFormat = str_replace(array('a', 'A'), array('', ''), $format);
1689 $newDate = $this->swap_formats($date, $noMerFormat, $fakeMerFormat);
1690 return str_replace('@~@', $mer, $newDate);
1694 * @deprecated for public use
1695 * Convert date from one format to another
1697 * @param string $date
1698 * @param string $from
1702 public function swap_formats($date, $from, $to)
1704 return $this->_convert($date, $from, self::$gmtTimezone, $to, self::$gmtTimezone);
1708 * @deprecated for public use
1709 * handles offset values for Timezones and DST
1710 * @param $date string date/time formatted in user's selected format
1711 * @param $format string destination format value as passed to PHP's date() funtion
1712 * @param $to boolean
1713 * @param $user object user object from which Timezone and DST
1714 * @param $usetimezone string timezone name
1715 * values will be derived
1716 * @return string date formatted and adjusted for TZ and DST
1718 function handle_offset($date, $format, $to = true, $user = null, $usetimezone = null)
1720 $tz = empty($usetimezone)?$this->_getUserTZ($user):new DateTimeZone($usetimezone);
1721 $dateobj = new SugarDateTime($date, $to? self::$gmtTimezone : $tz);
1722 $dateobj->setTimezone($to ? $tz: self::$gmtTimezone);
1723 return $dateobj->format($format);
1724 // return $this->_convert($date, $format, $to ? self::$gmtTimezone : $tz, $format, $to ? $tz : self::$gmtTimezone);
1728 * @deprecated for public use
1729 * Get current GMT datetime in DB format
1732 function get_gmt_db_datetime()
1734 return $this->nowDb();
1738 * @deprecated for public use
1739 * Get current GMT date in DB format
1742 function get_gmt_db_date()
1744 return $this->nowDbDate();
1748 * @deprecated for public use
1749 * this method will take an input $date variable (expecting Y-m-d format)
1750 * and get the GMT equivalent - with an hour-level granularity :
1751 * return the max value of a given locale's
1752 * date+time in GMT metrics (i.e., if in PDT, "2005-01-01 23:59:59" would be
1753 * "2005-01-02 06:59:59" in GMT metrics)
1757 function handleOffsetMax($date)
1759 $min = new DateTime($date, $this->_getUserTZ());
1760 $min->setTime(0, 0);
1761 $max = new DateTime($date, $this->_getUserTZ());
1762 $max->setTime(23, 59, 59);
1764 $min->setTimezone(self::$gmtTimezone);
1765 $max->setTimezone(self::$gmtTimezone);
1767 $gmtDateTime['date'] = $this->asDbDate($max, false);
1768 $gmtDateTime['time'] = $this->asDbDate($max, false);
1769 $gmtDateTime['min'] = $this->asDb($min);
1770 $gmtDateTime['max'] = $this->asDb($max);
1772 return $gmtDateTime;
1776 * @deprecated for public use
1777 * this returns the adjustment for a user against the server time
1779 * @return integer number of minutes to adjust a time by to get the appropriate time for the user
1781 public function adjustmentForUserTimeZone()
1783 $tz = $this->_getUserTZ();
1784 $server_tz = new DateTimeZone(date_default_timezone_get());
1785 if ($tz && $server_tz) {
1786 return ($server_tz->getOffset($this->now) - $tz->getOffset($this->now)) / 60;
1792 * @deprecated for public use
1793 * assumes that olddatetime is in Y-m-d H:i:s format
1794 * @param $olddatetime
1797 function convert_to_gmt_datetime($olddatetime)
1799 if (! empty($olddatetime)) {
1800 return date('Y-m-d H:i:s', strtotime($olddatetime) - date('Z'));
1806 * @deprecated for public use
1807 * get user timezone info
1811 public function getUserTimeZone(User $user = null)
1813 $tz = $this->_getUserTZ($user);
1814 return array("gmtOffset" => $tz->getOffset($this->now) / 60);
1818 * @deprecated for public use
1819 * get timezone start & end
1821 * @param string $zone
1824 public function getDSTRange($year, $zone = null)
1827 $tz = timezone_open($zone);
1830 $tz = $this->_getUserTZ();
1833 $year_date = SugarDateTime::createFromFormat("Y", $year, self::$gmtTimezone);
1834 $year_end = clone $year_date;
1835 $year_end->setDate((int) $year, 12, 31);
1836 $year_end->setTime(23, 59, 59);
1837 $year_date->setDate((int) $year, 1, 1);
1838 $year_date->setTime(0, 0, 0);
1840 $transitions = $tz->getTransitions($year_date->ts, $year_end->ts);
1842 if(version_compare(PHP_VERSION, '5.3.0', '<')) {
1843 // <5.3.0 ignores parameters, advance manually to current year
1844 $start_ts = $year_date->ts;
1845 while(isset($transitions[$idx]) && $transitions[$idx]["ts"] < $start_ts) $idx++;
1848 while (isset($transitions[$idx]) && !$transitions[$idx]["isdst"]) $idx++;
1849 if(isset($transitions[$idx])) {
1850 $result["start"] = $this->fromTimestamp($transitions[$idx]["ts"])->asDb();
1853 while (isset($transitions[$idx]) && $transitions[$idx]["isdst"]) $idx++;
1854 if(isset($transitions[$idx])) {
1855 $result["end"] = $this->fromTimestamp($transitions[$idx]["ts"])->asDb();
1860 /****************** GUI stuff that really shouldn't be here, will be moved ************/
1862 * Get Javascript variables setup for user date format validation
1863 * @deprecated moved to SugarView
1864 * @return string JS code
1866 function get_javascript_validation()
1868 return SugarView::getJavascriptValidation();
1873 * This method renders a <select> HTML form element based on the
1874 * user's time format preferences, with give date's value highlighted.
1876 * If user's prefs have no AM/PM string, returns empty string.
1878 * @todo There is hardcoded HTML in here that does not allow for localization
1879 * of the AM/PM am/pm Strings in this drop down menu. Also, perhaps
1880 * change to the substr_count function calls to strpos
1881 * TODO: Remove after full switch to fields
1883 * @param string $prefix Prefix for SELECT
1884 * @param string $date Date in display format
1885 * @param string $attrs Additional attributes for SELECT
1886 * @return string SELECT HTML
1888 function AMPMMenu($prefix, $date, $attrs = '')
1890 $tf = $this->get_time_format();
1891 $am = strpbrk($tf, 'aA');
1895 $selected = array("am" => "", "pm" => "", "AM" => "", "PM" => "");
1896 if (preg_match('/([ap]m)/i', $date, $match)) {
1897 $selected[$match[1]] = " selected";
1900 $menu = "<select name='" . $prefix . "meridiem' " . $attrs . ">";
1901 if ($am{0} == 'a') {
1902 $menu .= "<option value='am'{$selected["am"]}>am";
1903 $menu .= "<option value='pm'{$selected["pm"]}>pm";
1905 $menu .= "<option value='AM'{$selected["AM"]}>AM";
1906 $menu .= "<option value='PM'{$selected["PM"]}>PM";
1909 return $menu . '</select>';
1913 * Get user format in JS form
1914 * TODO: Remove after full switch to fields
1917 function get_user_date_format()
1919 return str_replace(array('Y', 'm', 'd'), array('yyyy', 'mm', 'dd'), $this->get_date_format());
1923 * Get user time format example
1924 * TODO: Remove after full switch to fields
1928 function get_user_time_format()
1930 global $sugar_config;
1931 $time_pref = $this->get_time_format();
1933 if (! empty($time_pref) && ! empty($sugar_config['time_formats'][$time_pref])) {
1934 return $sugar_config['time_formats'][$time_pref];
1937 return '23:00'; //default