php时间转换,从a时区转换到b时区
<?php /** * Created by PhpStorm. * User: lxd * Date: 2019/1/9 * Time: 13:25 * Comm: */ class DtFormat { protected $dt; protected $ttz; //目标时区 protected static $instance; private function __construct( $ftz, $ttz ) { if( !$ftz || !$ftz instanceof DateTimeZone ) $ftz = new DateTimeZone( date_default_timezone_get() ); //默认来源时区 if( !$ttz || !$ttz instanceof DateTimeZone ) $this->ttz = new DateTimeZone( C('PARTNER_TIME_ZONE') ); //默认输出时区 else $this->ttz = $ttz; $this->dt = new DateTime( 'now', $ftz ); } /** * author liuxiaodong * date 2019/1/11 15:19 * @param null $ftz 来源时区 * @param null $ttz 目标时区 * @return DtFormat */ public static function getInstance( $ftz = null, $ttz = null ) { if( !$ftz && !$ttz ) $key = '0'; else { $ftz_key = $ftz instanceof DateTimeZone ? $ftz->getName() : null; $ttz_key = $ttz instanceof DateTimeZone ? $ttz->getName() : null; $key = md5( $ftz_key . $ttz_key ); } if( !self::$instance[$key] instanceof self ) { self::$instance[$key] = new self( $ftz, $ttz ); } return self::$instance[$key]; } public function show( $original, $formart = 'Y-m-d H:i:s' ) { //将时间转成时间戳 $new_original = @($original + 0); if (strlen($new_original) != strlen($original)) { $new_original = strtotime($original); if (!$new_original) return $original; } /** * notice * 时区不一致,同一个时间转换成时间戳是不一样的 !! * $str = '2018-09-26 07:23:31'; var_dump( date_default_timezone_get() ); //UTC var_dump( strtotime( $str ) ); //1537946611 date_default_timezone_set( 'PRC' ); var_dump( strtotime( $str ) ); //1537917811 * */ $datetime = null; if( $this->dt->getTimezone()->getName() == date_default_timezone_get() ) { $datetime = clone $this->dt; $datetime = $datetime->setTimestamp($new_original); }else { $tmpDt = new DateTime(); $tmpDt->setTimestamp( $new_original );
$datetime = DateTime::createFromFormat( 'Y-m-d H:i:s', $tmpDt->format( 'Y-m-d H:i:s' ), $datetime->getTimezone() );
} $datetime->setTimezone($this->ttz); return $datetime->format( $formart ); } }
调用:
try{ $timestr = '2018-10-10 12:00:00'; $ftimezone = new \DateTimeZone( 'UTC' ); $ttimezone = new \DateTimeZone( 'PRC' ); $newtm = \DtFormat::getInstance( $ftimezone, $ttimezone )->show( $timestr ); echo( "old = {$timestr}; new = {$newtm}" ); }catch ( \Exception $e ) { //error }
结果: old = 2018-10-10 12:00:00; new = 2018-10-10 20:00:00
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端