Convert DateTime class to string
64,086
Solution 1
in php you can simply use 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
Solution 2
The following code will give you a date usable for 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');
Solution 3
Use CONVERT
:
SELECT CONVERT(VARCHAR(10), datefield, 121)
FROM tablename;
Author by
Genjo
Updated on October 23, 2020Comments
-
Genjo over 3 years
Currently I am retrieving a date from mssql with the data type of small date time.
The data is :
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-12
on the text box.The message I get is:
catchable fatal error : Object of class DateTime could not be converted to string.
Any idea?
-
Genjo about 11 yearsI jusst replace the datefield with the column name i use in my database? What is 121?
-
Mahmoud Gamal about 11 years@Genjo - It determine the style of the formated date for the conversion, with
121
it gives you the date in the format:yyyy-mm-dd hh:mi:ss.mmm
, then convert it to onlyVARCHAR(10)
will give you:yyyy-mm-dd
. -
ta.speot.is about 11 yearsI prefer to handle presentation in the presentation layer.
-
Admin almost 7 yearsI can't understand why this isn't the accepted answer...