PDO可以将日期作为DateTime对象返回吗?

时间:2017-07-03 06:52:15

标签: php sql-server datetime pdo

Microsoft的PHP SQL Server驱动程序可以将日期作为本机PHP DateTime对象返回,但是当通过PDO访问时,日期将作为字符串返回。有没有办法配置PDO以将日期作为对象返回?

<?php
$server = 'localhost\\SQLEXPRESS';
$database = 'MyDatabase';
$username = 'MyUsername';
$password = 'MyPassword';
$sql = 'SELECT CAST(\'2017-01-31\' AS DATE) AS [Col1], \'2017-01-31\' AS [Col2]';

// Microsoft driver
$conn = sqlsrv_connect($server,
                       ['UID' => $username, 'PWD' => $password, 'Database' => $database,]);
$statement = sqlsrv_prepare($conn, $sql);
sqlsrv_execute($statement);
while ($row = sqlsrv_fetch_array($statement, SQLSRV_FETCH_ASSOC)) {
    var_dump($row);
}
/*
array (size=2)
  'Col1' => 
    object(DateTime)[1]
      public 'date' => string '2017-01-31 00:00:00.000000' (length=26)
      public 'timezone_type' => int 3
      public 'timezone' => string 'Australia/Canberra' (length=18)
  'Col2' => string '2017-01-31' (length=10)
*/

// PDO
$pdo_conn = new PDO("sqlsrv:Server={$server};Database={$database}", $username, $password);
foreach ($pdo_conn->query($sql) as $row) {
    var_dump($row);
}
/*
array (size=4)
  'Col1' => string '2017-01-31' (length=10)
  0 => string '2017-01-31' (length=10)
  'Col2' => string '2017-01-31' (length=10)
  1 => string '2017-01-31' (length=10)
*/

微软的驱动程序可以区分日期和文本列,而显然,PDO不能。它甚至包括时区!如代码所示,使用PDO,在查询运行之后,PHP代码需要知道Col1(但不包含相同字符串的Col2)应该是DateTime对象并手动转换它。由于数据库已经知道字段的类型,无论是直接从表中拉出还是计算结果,是否有办法在PDO中访问此信息?

0 个答案:

没有答案