跨时区日期转换

源文件在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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值