America/Central MySql 的时间没有节省正确的时间

America/Central time in MySql is not saving right time

我正在尝试将我的记录保存为我的 MySql 数据库中的中部时间。不过好像时间不对。

Field: added_on
Data type: TIMESTAMP
Default: CURRENT_TIMESTAMP

PHP:

$now = date('Y/m/d H:i:s' );
$date = new DateTime( $now, new DateTimeZone( 'America/Chicago' ) );

$sql = $conn->prepare( "INSERT INTO agent_notes
            (agent_code, account_code, agent_note, added_on)
            VALUES (?, ?, ?, ?)" );

$sql->execute( array( $agent_code, $account_code, $agent_note, $date ) );

我指的是https://www.php.net/manual/en/timezones.america.php#114172

在发布 CST 时当前时间是 2:36 am, Wednesday, 29 April 2020
保存在我服务器数据库中的日期是 7:36 am, Wednesday, 29 April 2020

虽然我期待它与上面的 CST 相同,即 2:36 am, Wednesday, 29 April 2020

服务器:GoDaddy

我做错了什么?

它正在存储正确的值:UTC 时间戳。如果您想在获取数据时将其转换回本地时区,您可以这样做,但是 MySql 中的 TIMESTAMP 字段没有时区。

来自MySql TIMESTAMP tutorial

When you insert a TIMESTAMP value into a table, MySQL converts it from your connection’s time zone to UTC for storing.

同样来自 reference documentation

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time. The time zone can be set on a per-connection basis. As long as the time zone setting remains constant, you get back the same value you store.

因此,如果您使用指定时区的连接从数据库中获取数据,您应该在该时区取回数据 - 但如果您只是浏览以其他方式访问数据库,或者如果您在 没有在连接中指定时区 的情况下获取它,您将获得 UTC。

这完全适合时间戳。是not always appropriate for future dates and times,但那是另一回事。