【问题标题】:strtotime() time zone warning. Storing a simple Unix Timestamp in a MySQL database with UTC Timezone [duplicate]strtotime() 时区警告。使用UTC时区在MySQL数据库中存储一个简单的Unix时间戳[重复]
【发布时间】:2026-02-09 00:05:02
【问题描述】:

这是我收到的警告:

PHP 警告:strtotime():依赖系统的时区设置是不安全的。您需要使用 date.timezone 设置或 date_default_timezone_set() 函数。如果您使用了这些方法中的任何一种,但仍然收到此警告,您很可能拼错了时区标识符。我们在第 38 行的 /data1/home/spaceweather/Scripts/casesFiles_InsertIntoDataBase.php 中为“CST/-6.0/no DST”选择了“America/Chicago”

这是我用来在脚本中设置时区的代码。

我正在尝试消除 PHP 警告并将其指定为 UTC 到 strtotime() 而不是我系统上的默认时区。 (附:黑鹰队!)

$year = substr($filePath[$row], -17,4);  //where this outputs a simple year 'CCYY'
$day = $days2[$days2keys[$i]];           //where this provides the day of year
$format = 'Y-z';                          //specifying what format i'm creating the datetime with
$date = $year . '-' . $day;             //formatting the strings to the above $format
$timezone = new DateTimeZone('UTC');     //specify the timezone
$fileDateStore[$row] = DateTime::createFromFormat($format, $date, $timezone);  //create the DateTime object
$fileDateString[$row] = date_format($fileDateStore[$row],"Y-m-d".PHP_EOL);  //format it so strtotime() can read it
$fileDate[$row] = strtotime($fileDateString[$row]);  //finally create the Unix Timestamp for the date.

然后我使用以下代码将其存储到数据库中:

//connect to the database
$con=mysqli_connect("server","database","username","password");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
for($j = 1; $j < $numrows; $j++) {
    $date = $fileDate[$j]; 
    mysqli_query($con,"INSERT INTO tablename (fileDate) 
    VALUES (".$date.")");
}
mysqli_close($con);
echo "task finished and database connection closed.".PHP_EOL;

【问题讨论】:

  • 你有什么问题?我看不出你已经完成了消息中所说的任何事情。
  • 参见上面的编辑。对不起!
  • 您需要使用 date.timezone 设置或 date_default_timezone_set() 函数...并且您编辑以添加您的 SQL 代码??
  • 只是想让帖子更完整。对不起。在最后添加 SQL 似乎可能会有所帮助,并且是事后才想到的 XD。
  • 对不起,阿尔瓦罗,我想我的问题令人困惑。如果您在我的代码中注意到我输入了$timezone = new DateTimeZone('UTC'); 行,我希望它转到那个时区,而不是我的默认时区。非常抱歉给您带来的困惑,感谢您的帮助。

标签: php mysql datetime timezone strtotime


【解决方案1】:

编辑您的php.ini文件并添加类似于

date.timezone = America/Chicago

或者,您可以在代码中使用date_default_timezone_set() 函数:

date_default_timezone_set('America/Chicago');

有关有效值的列表,请查看http://php.net/manual/en/timezones.php

【讨论】:

  • 感谢您的帮助 user2534880。我把我的问题搞糊涂了。我想通过这行代码$timezone = new DateTimeZone('UTC'); 将时区设置为“UTC”,但由于某种原因我仍然收到错误消息。我认为这个答案是如何更改所有 php 相关函数的默认时区?
  • 您收到错误是因为您忽略了它提供的说明。当有人帮助将它们复制到答案中时,您甚至会忽略这些说明。您对我们如何说服您更改date.timezone 或致电date_default_timezone_set() 有什么建议吗?
  • 设置默认时区不会阻止您在创建的 DateTime 对象上指定不同的 DateTimeZone(例如 UTC)。但它会使警告消失。
  • 好的,所以我想我对 date_default_timezone_set() 的行为感到困惑。它看起来像一个在整个脚本中设置时区的函数。如果我是存储具有多个时区或不同时区的日期的人怎么办?如果我将此 date_default_timezone_set() 函数放在脚本的顶部,我以后如何更改该时区?我可以将该行放在脚本中的多个点中吗?抱歉,我是 php 新手。
  • 好的,我现在明白错误源于 php 没有设置默认值,并且它依赖于我的系统。我现在遇到的一个问题是我需要联系我的主机管理员来更改它,因为 php.ini 文件位于我拥有权限的目录之外:(.
最近更新 更多