什么决定(如何配置)php PDO 驱动程序对日期和时间戳字段的值使用什么格式字符串?

What determines (how to configure) what format string is used by php PDO driver for values of date and timestamp fields?

我有 Firebird 3.0 数据库,它有日期和时间戳字段,我在 PHP 7.x 中使用 interbase 扩展(是的 - 仍然是 interbase)和 Yii2 框架。我有 Yii 代码:

Yii::$app->db->createCommand('select order_date from orders where order_id=5');

哪个 returns 字段的值为:

2019-10-15 00:00:00

AFAIU 然后 Yii2 使用 PDO,这就是为什么我的问题减少到关于 PDO 的问题。 PHP 具有 DateTime 扩展名,但 AFAIU PDO 不使用 DateTime class(并且也不使用 Unix 时间戳 - 整数秒),而是根据某种格式仅 returns 字符串。

我的问题是 - PDO 层对 SQL 日期和时间戳字段使用什么格式字符串,我如何更改该格式字符串?我想确保返回的日期或时间戳采用指定格式,我可以从中创建 DateTime 实例并进一步操作该实例。例如。 Firebird 3.0 还没有时区,这就是为什么我想调用 $dateTimeInstance->setTimezone(...) 来完全指定实例的时区部分,然后我可以安全地输出 const string DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO" 格式的值,这是普遍接受的日期时间格式JSON>

如果您希望在 Yii2 中全局配置格式,您应该在通用配置中设置一些本地化设置:

配置示例

'timeZone' => 'America/New_York', // Default PHP date in Eastern.
//... other config stuff
'components' => [
    'formatter' => [
        'dateFormat' => 'php:Y-m-d',
        'datetimeFormat' => 'php:Y-m-d H:i:s',
        'decimalSeparator' => '.',
        'thousandSeparator' => ',',
        'defaultTimeZone' => 'UTC',       // DB Source is stored as UTC timezone.
        'timeZone' => 'America/New_York', // When formatter is used, convert to this timezone.
    ],
    //... other config stuff
  ]

时间检查

管理本地化时区可能会很麻烦,因此创建一个页面以便您更好地理解本地化格式。参见 Yii2 Internationalization Docs

<?php
$now = (new \yii\db\Query)->select('NOW()')->scalar(Yii::$app->db);
?>
<table class="table">
    <tr>
        <th>PHP UTC dateTime (+4 Hours):</th>
        <td><?= gmdate('Y-m-d H:i:s')?></td>
    </tr>
    <tr>
        <th>PHP local dateTime:</th>
        <td><?= date('Y-m-d H:i:s')?></td>
    </tr>
    <tr>
        <th>PHP local timeZone:</th>
        <td><?= date_default_timezone_get() ?></td>
    </tr>
    <tr>
        <th>Database Time Raw (expected UTC):</th>
        <td><?= $now ?></td>
    </tr>
    <tr>
        <th>Formatter -> UTC to local dateTime:</th>
        <td><?= Yii::$app->formatter->asDatetime(gmdate('Y-d-m H:i:s')) ?></td>
    </tr>
    <tr>
        <th>Formatter -> realtiveTime from UTC:</th>
        <td><?= Yii::$app->formatter->asRelativeTime(gmdate('Y-m-d H:i:s')) ?></td>
    </tr>
</table>