*/ /** * patTemplate modfifier Dateformat * * Formats dates and times according to a format string and locale settings. * This modifier is derived from the original one extended with capability * to calculate offsets according to timezone. * * Possible attributes are: * - format (string) * - unix (bool) if not empty, return unix timestamp * - dateinterval (string) see https://www.php.net/manual/en/dateinterval.construct.php also accepts "-" prefix * - adjustoffset (string, default "auto") * auto: add offset according to timezone * any number: add seconds * * See locale settings in "locale.xml" * * See the PHP documentation for strftime() for * more information. * * @package patTemplate * @package Modifiers * @author gERD Schaufelberger */ class patTemplate_Modifier_Dateformat extends patTemplate_Modifier { /** * configured timezone * @var DateTimeZone */ static private $timezone; /** * start timezone object */ static public function staticConstruct() { $conf = WBClass::create('WBConfig'); $conf->load('locale'); self::$timezone = new DateTimeZone($conf->get('locale/timezone', 'UTC')); } /** * modify the value * * Format date time. The input value may either be a unix timestamp or ISO * date as used in MySQL. All input values are supposed to be UTC. * * In case the input value contains hours and minutes (not just the date), * local time offset will be added. See local settings in etc/locale.xml * * @access public * @param string value * @return string modified value */ public function modify($value, $params = array()) { $adjustTimeOffset = false; // convert unix timestamp to ISO date if (preg_match('/^[0-9]+$/', $value)) { $value = gmdate('Y-m-d H:i:s', $value); $adjustTimeOffset = true; } if (preg_match('/\d\d:\d\d/', $value, $match)) { $adjustTimeOffset = true; } $params = array_merge(array( 'adjustoffset' => 'auto', 'dateinterval' => '', 'unix' => '', 'format' => '' ), $params); // init timezone if (empty(self::$timezone)) { self::staticConstruct(); } try{ $date = new DateTime($value); } catch (Exception $e) { return $value; } // date interval if (!empty($params['dateinterval'])) { if ('-' == $params['dateinterval'][0]) { $di = new DateInterval(substr($params['dateinterval'], 1)); $date->sub($di); } else { $di = new DateInterval($params['dateinterval']); $date->add($di); } } $ts = intval($date->format('U')); // return unix timestamp if ('yes' == $params['unix']) { return $ts; } if ($adjustTimeOffset) { $offset = $params['adjustoffset']; if ('auto' == $offset) { $offset = self::$timezone->getOffset($date); } else if (is_numeric($offset)) { $offset = intval($offset); } else { $offset = 0; } $ts += $offset; } // in case there is no format string, return in unix timestamp format if (empty($params['format'])) { return $ts; } // apply format return strftime($params['format'], $ts); } }