如何将DateTime内的ISO时间转换为本地时间?

时间:2018-04-23 08:29:49

标签: php mysql php-7

我像这样创建一个DateTime对象

$timestamp = new DateTime('2018-04-23T07:01:05.146000+00:00');
$timestampSql = $messageTimestamp->format('Y-m-d H:i:s');
然后我将$ timestampSql插入到mysql表的时间戳字段中。但问题是,mysql认为这个时间和日期是在mysql服务器的任何时区,并没有意识到,它实际上源于ISO时间。

基本上,我需要以某种方式确保 - >格式输出转换为服务器设置的当前时区的时间戳。

2 个答案:

答案 0 :(得分:0)

以下是一种使用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');

}

答案 1 :(得分:0)

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

$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;
    }
}