【问题标题】:How can I construct a reusable DateTime object in CL?如何在 CL 中构造可重用的 DateTime 对象?
【发布时间】:2015-05-10 02:51:09
【问题描述】:

我一直在尝试在 CodeIgniter 中构造一个DateTime object。我正在从库中加载它。但我似乎无法用给定的 $time_zone 参数构造 DateTime() 。

我能看到这种情况的唯一方法是在所有方法中添加 DateTime 对象。

这是使用 mvc 的一大缺点。有没有人有替代方案?

我的代码:

class Create_Timestamp 
{
     private $date_time;

     /**
     * @param $time_zone : gets passed in from a cookie. Cookie value is an array that gets retrieved from the DB. In the
     * array there time zone value
     * @return int
     */

     public function __construct($time_zone)
     {
         $this->date_time = new DateTime("now", new DateTimeZone($time_zone));
     }

     public function TimeStamp()
     {
       $time_stamp =  $this->date_time->getTimestamp();
       return $time_stamp;
      }

      public function convertTimeStamp($unix_time_stamp)
      {
           fb($unix_time_stamp);
           $this->date_time->createFromFormat("m/d/Y", $unix_time_stamp);
           //$this->date_time->setTimestamp($unix_time_stamp);
           $formatted_time_stamp = $this->date_time->format("m/d/Y h:i:s A");
    return $formatted_time_stamp;
     }
}

【问题讨论】:

  • 请记住格式化您的代码。

标签: php codeigniter datetime


【解决方案1】:

不要重新发明轮子做 PIE(自豪地在别处发明)。你会为自己和他人免去很多痛苦。

Carbon 包为例。

如果您有幸使用 CI v.3,只需转到您的应用程序文件夹并执行

$ composer require nesbot/carbon

并开始使用它

Carbon\Carbon::createFromTimestamp($time_stamp, $time_zone)->toDateTimeString();

如果您使用 CI v.2.X 仍然利用 composer。转到您的应用根目录并执行

$ composer require nesbot/carbon

然后在你的index.php 添加

require './vendor/autoload.php'; // or whatever the path would be in your case

【讨论】:

    猜你喜欢
    • 2015-04-14
    • 2012-09-21
    • 2019-09-12
    • 1970-01-01
    • 2020-03-04
    • 2018-02-22
    • 2023-03-13
    • 1970-01-01
    • 2018-12-13
    相关资源
    最近更新 更多