源文件在C位
<?php
/**
* Class TimeZone
*/
class TimeZone
{
protected static $_instance = null;
protected $from = 'Asia/Shanghai';
protected $to = 'Asia/Shanghai';
protected $format = 'Y-m-d H:i:s';
const INVALID_TIMEZONE = "Invalid timezone %s";
const CREATE_DATETIME_ERROR = "DateTime::createFromFormat error";
/**
* 时间转换
* @param $dateTime
* @return array|string
*/
public function dateTimeChangeByZone($dateTime)
{
try {
if ($this->from == $this->to) return $dateTime;
if (!self::validateTimeZone($this->to)) throw new \Exception(sprintf(self::INVALID_TIMEZONE,$this->to));
if (!self::validateTimeZone($this->from)) throw new \Exception(sprintf(self::INVALID_TIMEZONE,$this->from));
$dateTimeZoneFrom = new \DateTimeZone($this->from);
$dateTimeZoneTo = new \DateTimeZone($this->to);
$dateTimeObj = DateTime::createFromFormat($this->format, $dateTime, $dateTimeZoneFrom);
if ($dateTimeObj === false) throw new \Exception(self::CREATE_DATETIME_ERROR);
$dateTimeObj->setTimezone($dateTimeZoneTo);
return $dateTimeObj->format($this->format);
}catch (\Exception $exception) {
return ['error' => $exception->getMessage()];
}
}
// 获取实例
public static function getInstance()
{
if (!self::$_instance) self::$_instance = new self();
return self::$_instance;
}
public function assignData($params = [])
{
$to = $params['to'] ?: '';
$from = $params['from'] ?: '';
$format = $params['format'] ?: '';
$to && $this->to = $to;
$from && $this->from = $from;
$format && $this->format = $format;
return $this;
}
/**
* @param $timezone string 时区
* @return bool
*/
private static function validateTimeZone($timezone)
{
return in_array($timezone, DateTimeZone::listIdentifiers());
}
private function __construct(){}
private function __clone(){
// TODO: Implement __clone() method.
}
}
测试代码
// 测试代码
$time = date('Y-m-d H:i:s');
$params = [
'from' => 'Asia/Shanghai',
'to' => 'America/New_York',
'format' => 'Y-m-d H:i:s',
];
$transform_data = TimeZone::getInstance()->assignData($params)->dateTimeChangeByZone($time);
echo $params['to'],":";var_dump($transform_data);
echo $params['from'],":";var_dump(date('Y-m-d H:i:s'));
echo "default timezone:";
var_dump( date_default_timezone_get());
// 输出结果
America/New_York:string(19) "2022-07-08 03:28:22"
Asia/Shanghai:string(19) "2022-07-08 15:28:22"
default timezone:string(3) "UTC"
原文地址:https://www.xxshare.cn/topics/62/kua-shi-qu-zhuan-huan-ri-qi