/** * This function can convert 3 date formats: * - 2019-11-20T15:34:03.000+0300 * - 2019-11-19T17:21:53Z * - unix time with 000 at the end * @param type $timestamp * @return date("Y-m-d H:i:s") with app default timezone */ function dateTimeFormat($timestamp = NULL) { if ((empty($timestamp)) || (is_null($timestamp)) || (is_object($timestamp)) || (is_array($timestamp))) { return $timestamp; } elseif (is_numeric($timestamp) && (strlen($timestamp) == 13) && (substr($timestamp, -3) == "000")) { $timestamp = substr($timestamp, 0, -3); return $this->getTime($timestamp, date_default_timezone_get()); } elseif (preg_match('/^' . '(\d{4})-(\d{2})-(\d{2})T' . // YYYY-MM-DDT ex: 2014-01-01T '(\d{2}):(\d{2}):(\d{2})' . // HH-MM-SS ex: 17:00:00 '(Z|((-|\+)\d{2}:\d{2}))' . // Z or +01:00 or -01:00 '$/', $timestamp, $parts) == true) { return $this->getTime(strtotime($timestamp), date_default_timezone_get()); } elseif (preg_match('/^' . '(\d{4})-(\d{2})-(\d{2})T' . // YYYY-MM-DDT ex: 2014-01-01T '(\d{2}):(\d{2}):(\d{2})' . // HH-MM-SS ex: 17:00:00 '(.\d{3})' . '(((-|\+)\d{4}))' . // Z or +01:00 or -01:00 '$/', $timestamp, $parts) == true) { $timestamp = str_replace("T", ' ', substr($timestamp, 0, 19)); return $this->getTime(strtotime($timestamp), date_default_timezone_get()); } return $timestamp; } /** * Return date for specific timezone * @param type $timestamp input: 1518404518,America/Los_Angeles * @param type $timezone * @return type */ function getTime($timestamp, $timezone) { try { $date = new DateTime(date("Y-m-d H:i:s", $timestamp)); $date->setTimezone(new DateTimeZone($timezone)); $rt = $date->format('Y-m-d H:i:s'); /* output: Feb 11, 2018 7:01:58 pm */ return $rt; } catch (\Exception $e) { log_message('error', "Library->Helpers::ts2time: Error on time conversion: $timestamp | $e"); return ""; } }
Tutorials