【问题标题】:Change timezone of given register in MYSQL with PHP使用 PHP 更改 MYSQL 中给定寄存器的时区
【发布时间】:2017-03-03 10:50:08
【问题描述】:

我们将欧洲/马德里时间的日期作为日期时间存储在我们的 MySQL 表中,在 PHP 中我们称之为 $h

$h 的格式是 2017-03-03 17:30:00

我想知道是否有一种简单的方法可以将这个时间($h)转换为另一个时区

类似

$h1=changetimezone ($h, 'Europe/Madrid', 'Europe/Dublin')

其中 h1 是 h-1 小时

这个例子的结果是 2017-03-03 16:30:00

谢谢

编辑

我试过了

$h1 = new DateTime($h, new DateTimeZone('Europe/Madrid'));
$h1->setTimeZone(new DateTimeZone('Europe/Dublin'));

但我有

$f=strftime('%e/%m/%y %H:%M', strtotime($h1));

我明白了

 strtotime() expects parameter 1 to be string, object given 

编辑 2:

原始 $h vardump:

string(19) "2017-03-03 17:30:00"

但它在 MySQL 中存储为日期时间

【问题讨论】:

    标签: php mysql timezone


    【解决方案1】:

    你可以使用DateTime date_timezone_set ( DateTime $object , DateTimeZone $timezone )

    http://php.net/manual/en/datetime.settimezone.php

    【讨论】:

      【解决方案2】:

      回答您的编辑。先试试这个

      $h1 = new DateTime($h, new DateTimeZone('Europe/Madrid'));
      $h1->setTimeZone(new DateTimeZone('Europe/Dublin'));
      
      echo "<pre>";
      var_dump($h1);
      

      如您所见,这是一个 DateTime 对象,无法直接使用 strtotime 进行转换,因为此函数等待字符串。试试:

      $h1->format('Y-m-d H:i:s');
      

      这是一个字符串。

      第二次修改你的答案:

      <?php
      
      $h1 = new DateTime("2017-03-03 17:30:00", new DateTimeZone('Europe/Madrid'));
      
      echo "<pre>";
      var_dump($h1);
      
      $h1->setTimeZone(new DateTimeZone('Europe/Dublin'));
      
      var_dump($h1);
      
      var_dump($h1->format('Y-m-d H:i:s'));
      
      $f=strftime('%e/%m/%y %H:%M', strtotime($h1->format('Y-m-d H:i:s')));
      
      var_dump($f);
      

      我的结果picture

      【讨论】:

      • 这就是我正在尝试但不起作用的方法。我编辑了我的问题
      • 编辑了我的答案。查找Answer to your edit. Try this first 部分
      • 感谢您的帮助。第一个结果:object(DateTime)#1 (0) {} 第二个结果相同:strtotime() 期望参数 1 是字符串,给定对象
      • 在您的情况下$h 是什么?你能把它 var_dump 并粘贴到这里吗?
      • 完成。添加了 $h 的 vardump
      【解决方案3】:

      感谢Zoltan, here 解决。总结:

      $h1 = new DateTime($h, new DateTimeZone('Europe/Madrid')); 
      $h1->setTimeZone(new DateTimeZone($btz)); //$btz is users time zone 'Europe/Dublin'
      $f=strftime('%e/%m/%y %H:%M', strtotime($h1->format('Y-m-d H:i:s')));
      

      【讨论】:

        猜你喜欢
        • 2016-04-07
        • 2015-04-23
        • 1970-01-01
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多