将mssql datetime对象转换为PHP字符串 [英] Convert mssql datetime object to PHP string

查看:46
本文介绍了将mssql datetime对象转换为PHP字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据库中获取一些信息,并且该记录采用MSSQL DateTime格式,当我将其返回时,它在我的数组中显示如下:

I'm grabbing some information from a database and the record is in an MSSQL DateTime format, when I return it, it shows in my array as follows:

[arrayItem] => DateTime Object
    (
        [date] => 2008-06-05 09:14:11
        [timezone_type] => 3
        [timezone] => Europe/London
    )

当我尝试将其提取为数组(即 $ array [arrayItem] [date] )时,出现错误:

When I try to extract this as an array (ie $array[arrayItem][date]) I get an error:

致命错误:不能将DateTime类型的对象用作数组

Fatal error: Cannot use object of type DateTime as array

在将数据传递给PHP之前,我还尝试过使用SQL格式化数据,而strtotime函数并没有带来乐趣.

I have also tried formatting the data in SQL before it is passed to the PHP, and the strtotime functions and had no joy.

任何建议都将受到欢迎,我正在用这个把头发撕掉!

Any recommendations would be very welcome, I'm tearing my hair out with this one!

谢谢

推荐答案

这也吸引了我几次.

希望这对您有帮助:)

http://af-design.com/blog/2010/03/13/microsoft-sql-server-driver-for-php-returns-datetime-对象/

这是该页面在说什么的要旨,以防链接断开.

Here's the gist of what that page is saying, in case the link goes down.

查询定义为 datetime 的列时, Microsoft扩展返回一个DateTime对象.因此,如果您期望使用字符串,则需要相应地调整代码.

When querying against a column defined as a datetime, the native PHP SQL Server extension returns a string where as the Microsoft extension returns a DateTime object. So if you are expecting a string, you’ll need to adjust your code accordingly.

它继续说明您可以简单地向数据库请求中添加一个附加参数,指定您希望将日期作为字符串返回.只需添加 ReturnDatesAsStrings 参数,并指定 true .

It goes on to explain that you can simply add an additional parameter to your requests to the database, specifying that you want your dates to be returned as strings. Simply add the ReturnDatesAsStrings parameter, specifying true.

示例:

$connectionParams = array(
    'USR'=>'user',
    'PASS'=>'pass',
    'Database'='myDatabase',
    'ReturnDatesAsStrings'=>true  //<-- This is the important line
);
$conn = sqlsrv_connect('127.0.0.1',$connectionParams);

然后,您可以像常规连接sqlsrv数据库那样使用 $ conn ,只有日期将返回为字符串,而不是DateTime对象.

Then you can use $conn as you would regularly for your sqlsrv database connection, only dates will return as strings, instead of DateTime objects.

或者,如果您想要的只是日期时间之外的时间戳,您可以致电:

Alternately, if all you wanted was a timestamp out of the datetime you could call:

$myDateTimeObject->getTimestamp();

这篇关于将mssql datetime对象转换为PHP字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆