Extracting only date from datetime field (mysql) and assigning it to php variable
49,294
Solution 1
If you just want to display the date portion, you could use the DateTime
class:
echo DateTime::createFromFormat("Y-m-d H:i:s", "2012-12-24 12:13:14")->format("d/m/Y");
// 24/12/2012
//Edited for double echo typo.
Solution 2
There is a link I find extremely useful when it comes to date manipulations: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
one can easily find the solution there:
SELECT *, DATE(Invdate) as Inv_date ...
Solution 3
Do it directly in MySQL:
select DATE_FORMAT('2012-12-24 12:13:14', '%Y/%m/%d')
So your query will look like this:
SELECT DATE_FORMAT(Invdate, '%Y/%m/%d') FROM INVHDR WHERE Invdate BETWEEN '$startdat' AND '$enddat'
Author by
user1114409
Updated on August 01, 2022Comments
-
user1114409 almost 2 years
I am unable to assign only date to a php variable from
datetime
field of a MySQL table. I am using PHP 4, I know how to do it in PHP 5.Can someone help as to what is missing from the below php code.
$dc = mysql_query("SELECT * FROM INVHDR WHERE Invdate BETWEEN '2011-04-01' AND '2012-03-31'"); while ($dc2 = mysql_fetch_assoc($dc)) { $invno = $dc2['Invno']; // Here Invno is a datetime field type $invdat3 = $dc2['Invdate']; $date_array = explode("-", $invdat3); $invdat = sprintf('%02d/%02d/%4d', $date_array[2], $date_array[1], $date_array[0]); }
-
maček over 11 yearsThis works, but this isn't the answer. He should just be using the
DATE()
function in theSELECT
portion of his query. -
Salman A over 11 yearsI have reasons why he should be displaying/formatting dates in PHP.