php 将 DateTime 类转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15423721/
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
Convert DateTime class to string
提问by Genjo
Currently I am retrieving a date from mssql with the data type of small date time.
目前我正在从 mssql 中检索数据类型为 small date time 的日期。
The data is : 2013-03-12 00:00:00
数据是: 2013-03-12 00:00:00
I want to store it in a variable and then display on a text box.
我想将它存储在一个变量中,然后显示在一个文本框中。
And the format I want to display is just 2013-03-12on the text box.
我想显示的格式就2013-03-12在文本框中。
The message I get is:
我得到的消息是:
catchable fatal error : Object of class DateTime could not be converted to string.
可捕获的致命错误:无法将 DateTime 类的对象转换为字符串。
Any idea?
任何的想法?
回答by Acuao
in php you can simply use date_format($date, 'Y-m-d')
在 php 中你可以简单地使用 date_format($date, 'Y-m-d')
<?php
$date = date_create('2013-11-23 05:06:07');
echo date_format($date, 'Y-m-d');
?>
returns 2013-11-23
返回 2013-11-23
回答by DASPRiD
The following code will give you a date usable for SQL:
以下代码将为您提供可用于 SQL 的日期:
$dateTime->format(\DateTime::ISO8601);
-edit-
-编辑-
Actually, I just saw that you want it the other way around. In that case:
事实上,我刚刚看到你想要它反过来。在这种情况下:
$dateTime->format('Y-m-d');

