【问题标题】:Codeigniter Default Timezone IssueCodeigniter 默认时区问题
【发布时间】:2016-02-08 12:26:23
【问题描述】:

简介:我正在开发一个 CodeIgniter3.0.3 版本的应用程序。它是一个多租户应用程序。单个代码库根据用户登录连接到多个数据库(与不同的数据库交互)。每个用户可能来自全球不同的时区。我正在尝试应用以下代码。

date_default_timezone_set("Africa/Accra");
$time =  Date('Y-m-d h:i:s');echo $time;
$expiry=$this->db->get_where('settings', array('type' => 'registration_date'))->row()->description;
$timestamp=strtotime($expiry);
echo Date('Y-m-d h:i:s',$timestamp);

此代码的第二行相应地正确显示了时间,而最后一行显示了服务器时间。

设置表的描述栏为varchar类型,存储值如“2016-02-08 16:29:09”。

另外,如果我在最后一行之前添加 date_default_timezone_set("Africa/Accra"),它工作正常。

问题:我尝试在 index.php、config.php、控制器构造方法、创建辅助库中设置此属性,但似乎都没有。请问怎么解决?

编辑:存储在数据库中的日期值是在应用此 timezone_set 之前。之前数据库中没有偏移量。

到目前为止,我不知道每个用户的时区。我可以将其设置为 GMT 并相应地更新所有列。 我是否需要根据设置的时区更新所有现有的日期列?但是,如果任何用户更改他们喜欢的时区会发生什么?有没有其他解决方法?

【问题讨论】:

  • 更改 php.ini 文件中的默认时区
  • 我不能这样做,因为它会根据数据库设置而改变。对于每个用户,它可能会发生变化。

标签: php mysql codeigniter datetime timezone


【解决方案1】:

地点

date_default_timezone_set("Africa/Accra");

在 index.php 文件中

【讨论】:

  • 感谢您帮助 Dhruv,但我已经提到我也尝试过在 index.php、构造函数和助手中应用。对于给定的代码,它也不适用于最后一行。
【解决方案2】:

Dhruv 的回答在一定程度上有所帮助。但是显示以前存储的日期(在实施时区之前)是问题所在。然后跟进几篇SO文章得出了如下解决方案。

date_default_timezone_set("Asia/Kolkata"); 
$registered=$this->db->get_where('settings', array('type' => 'registration_date'))->row()->description;
$dt_obj = new DateTime($registered);
$dt_obj->setTimezone(new DateTimeZone('Africa/Accra'));
echo $dt_obj->format('Y-m-d H:i:s');

即首先根据服务器设置时区,检索数据并将其转换为显示

感谢question中提到的gzipp

【讨论】:

  • 其实你可以把它放在控制器/你从数据库读取的地方。
【解决方案3】:

在 config.php 中,添加/修改以下块:

/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';

请参阅this guide 了解更多信息。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2023-04-03
    • 2019-09-06
    相关资源
    最近更新 更多