【问题标题】:Create php DateTime object from unix timestamp, set timezone in one line从unix时间戳创建php DateTime对象,在一行中设置时区
【发布时间】:2017-03-26 02:30:48
【问题描述】:

我知道在 php 中,您可以从 unix 时间戳创建 DateTime 对象,并将其时区设置为多行,如下所示:

$date = new DateTime('@' . $timestamp);
$date_with_timezone = $date->setTimezone(new DateTimeZone('America/Chicago'));

但是,我想在一行中执行此操作。以下方法不起作用:

$date_with_timezone = new DateTime('@' . $timestamp, new DateTimeZone('America/Chicago'));

有没有办法从 unix 时间戳创建一个 php DateTime 对象,并在同一行设置一个时区?

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    不是一行,而是两行……

    <?php
    
    $timestamp = time();
    $TimeZone = 'Europe/Paris';
      
    $Date_Obj = new DateTime(null, new DateTimeZone($TimeZone));
    $Date_Obj->setTimestamp($timestamp);
    
    echo $Date_Obj->format('Y-m-d H:i');
    // get: 2021-12-09 02:36
    
    date_default_timezone_set($TimeZone);
    setlocale(LC_TIME,'fr_FR');
    
    echo strftime('%A %e %B %Y - %H:%M', $Date_Obj->getTimestamp() );
    // get: Thursday  9 December 2021 - 02:36 or in your lang 
    
    ?>
    

    【讨论】:

      【解决方案2】:

      时区文档中有一条注释:
      注意:

      当 $time 参数是 UNIX 时间戳(例如 @946684800)或指定时区(例如 2010-01-28T15:00:00+02:00)时,$timezone 参数和当前时区将被忽略。

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

      作为一种解决方法,您可以创建一个函数并传入时间戳和时区。然后,您可以实现将变量赋值保持在同一行的目标。在函数中,您可以使用时间戳创建 DateTime 对象,然后分配时区并返回它。

      【讨论】:

        【解决方案3】:

        在 PHP 5.4 版中引入了实例化类成员访问(例如(new foo)-&gt;bar())支持(参见release notes),因此您可以这样做:-

        $date = (new DateTime('@' . $timestamp))->setTimezone(new DateTimeZone('America/Chicago'));
        

        See it working

        【讨论】:

          猜你喜欢
          • 2012-06-23
          • 2012-10-07
          • 2011-05-18
          • 1970-01-01
          • 1970-01-01
          • 2014-01-09
          • 2020-12-16
          • 2020-11-21
          • 2010-11-19
          相关资源
          最近更新 更多