如何将datetime中的iso时间转换为本地时间?

euoag5mw  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(469)

我创建了这样一个datetime对象

$timestamp = new DateTime('2018-04-23T07:01:05.146000+00:00');
$timestampSql = $messageTimestamp->format('Y-m-d H:i:s');

然后将$timestampsql插入mysql表中的timestamp字段。但问题是,mysql认为这个时间和日期是在mysql服务器所在的任何时区,而没有意识到,它实际上来自iso时间。
所以基本上,我需要以某种方式确保->格式输出转换为服务器设置的当前时区的时间戳。

2nbm6dog

2nbm6dog1#

请检查以下服务器和用户时区的功能

$time_diff = get_timezone_offset('America/New_York');

if(! function_exists('get_timezone_offset'))
{
   /*get time differ user and server */
   function get_timezone_offset($remote_tz, $origin_tz = null) {
      if($origin_tz === null) {
          if(!is_string($origin_tz = date_default_timezone_get())) {
              return false; // A UTC timestamp was returned -- bail out!
          }
      }
      $origin_dtz = new DateTimeZone($origin_tz);
      $remote_dtz = new DateTimeZone($remote_tz);
      $origin_dt = new DateTime("now", $origin_dtz);
      $remote_dt = new DateTime("now", $remote_dtz);
      $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
      $offset =  $offset/60;
      return $offset;
  }
}

$current_date = date("Y-m-d h:i:sa");

$new_date = $this->time_differction($current_date,$time_diff);

if(! function_exists('time_differction'))
{   
    /*Return new date and time as per user time zone */
    function time_differction($date_time, $time_diff){
        $time = strtotime($date_time);
        $time = $time - ($time_diff * 60 );
        $date = date("Y-m-d H:i:s", $time);
        return $date;
    }
}
6ljaweal

6ljaweal2#

以下是使用datetime对象轻松切换时区的方法:

function convertDate($dateTime){

$utc = 'UTC';
$newTimZone = 'TimeZone';

$newDateTime = new DateTime($dateTime, new DateTimeZone($utc));
$newDateTime->setTimezone(new DateTimeZone($newTimZone));
return $newDateTime->format('Y-m-d H:i:s');

}

相关问题