4 * @file src/Util/DateTimeFormat.php
7 namespace Friendica\Util;
14 * @brief Temporal class
18 const ATOM = 'Y-m-d\TH:i:s\Z';
19 const MYSQL = 'Y-m-d H:i:s';
22 * convert() shorthand for UTC.
24 * @param string $time A date/time string
25 * @param string $format DateTime format string or Temporal constant
28 public static function utc($time, $format = self::MYSQL)
30 return self::convert($time, 'UTC', 'UTC', $format);
34 * convert() shorthand for local.
36 * @param string $time A date/time string
37 * @param string $format DateTime format string or Temporal constant
40 public static function local($time, $format = self::MYSQL)
42 return self::convert($time, date_default_timezone_get(), 'UTC', $format);
46 * convert() shorthand for timezoned now.
48 * @param string $format DateTime format string or Temporal constant
51 public static function timezoneNow($timezone, $format = self::MYSQL)
53 return self::convert('now', $timezone, 'UTC', $format);
57 * convert() shorthand for local now.
59 * @param string $format DateTime format string or Temporal constant
62 public static function localNow($format = self::MYSQL)
64 return self::local('now', $format);
68 * convert() shorthand for UTC now.
70 * @param string $format DateTime format string or Temporal constant
73 public static function utcNow($format = self::MYSQL)
75 return self::utc('now', $format);
79 * @brief General purpose date parse/convert/format function.
81 * @param string $s Some parseable date/time string
82 * @param string $tz_to Destination timezone
83 * @param string $tz_from Source timezone
84 * @param string $format Output format recognised from php's DateTime class
85 * http://www.php.net/manual/en/datetime.format.php
87 * @return string Formatted date according to given format
89 public static function convert($s = 'now', $tz_to = 'UTC', $tz_from = 'UTC', $format = self::MYSQL)
91 // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
92 // Provide some sane defaults regardless.
93 if ($tz_from === '') {
101 if (($s === '') || (!is_string($s))) {
106 * Slight hackish adjustment so that 'zero' datetime actually returns what is intended
107 * otherwise we end up with -0001-11-30 ...
108 * add 32 days so that we at least get year 00, and then hack around the fact that
109 * months and days always start with 1.
111 if (substr($s, 0, 10) <= '0001-01-01') {
112 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
113 return str_replace('1', '0', $d->format($format));
117 $from_obj = new DateTimeZone($tz_from);
118 } catch (Exception $e) {
119 $from_obj = new DateTimeZone('UTC');
123 $d = new DateTime($s, $from_obj);
124 } catch (Exception $e) {
125 logger('DateTimeFormat::convert: exception: ' . $e->getMessage());
126 $d = new DateTime('now', $from_obj);
130 $to_obj = new DateTimeZone($tz_to);
131 } catch (Exception $e) {
132 $to_obj = new DateTimeZone('UTC');
135 $d->setTimeZone($to_obj);
137 return $d->format($format);