php 从教义 2 中的日期时间对象以字符串形式获取日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7204866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get date as a string from datetime object in doctrine 2
提问by dean jase
In one of my entities, I have a protected property called insert_date
which is a datetime.
在我的一个实体中,我有一个受保护的属性,称为insert_date
日期时间。
When I extract the data afterwards, I don't get the date as a string, I get an object. My var dump:
当我之后提取数据时,我没有将日期作为字符串,而是得到一个对象。我的 var 转储:
<pre class='xdebug-var-dump' dir='ltr'> <b>object</b>(<i>DateTime</i>)[<i>1560</i>] <i>public</i> 'date' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'2011-08-26 12:40:29'</font> <i>(length=19)</i> <i>public</i> 'timezone_type' <font color='#888a85'>=></font> <small>int</small> <font color='#4e9a06'>3</font> <i>public</i> 'timezone' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'Europe/London'</font> <i>(length=13)</i> </pre><pre class='xdebug-var-dump' dir='ltr'> <b>object</b>(<i>DateTime</i>)[<i>1571</i>] <i>public</i> 'date' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'2011-08-26 12:40:29'</font> <i>(length=19)</i> <i>public</i> 'timezone_type' <font color='#888a85'>=></font> <small>int</small> <font color='#4e9a06'>3</font> <i>public</i> 'timezone' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'Europe/London'</font> <i>(length=13)</i>
I tried:
我试过:
foreach($dateObj as $date) {
}
But it doesn't extract ... How can I get the date property from this object? Even $insert_date->date
doesn't work.
但它没有提取......我怎样才能从这个对象中获取日期属性?甚至$insert_date->date
不起作用。
回答by Pramendra Gupta
use
用
if($dateObj)
{
$dateObj->format('Y-m-d H:i:s');
}
回答by Chase
To make sure that your $dateObj is an actual datetime obj use:
要确保您的 $dateObj 是实际的日期时间对象,请使用:
if($dateObj instanceof \DateTime){
$dateObj->format('Y-m-d H:i:s');
}
using "instanceof" checks that the object will have the required format function thus wont throw errors if it isnt.
使用“instanceof”检查对象是否具有所需的格式函数,因此如果不是,则不会抛出错误。