MySQL stores the date in my database (by default) as 'YYYY-MM-DD' The field type for my date is 'DATE' (I do not need any time storage).. Is there a simple way to change it by default to DD/MM/YYYY ?
I call up different dates in 2 different tables, and no where in any of my code do I have anything resembling a date variable or anything! Hopefully this is a straight forward change?
In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate));
MySQL uses yyyy-mm-dd format for storing a date value. This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want.
In a MySQL database, the DATE_FORMAT() function allows you to display date and time data in a changed format. This function takes two arguments. The first is the date/datetime to be reformatted; this can be a date/time/datetime/timestamp column or an expression returning a value in one of these data types.
In PHP, you could :
strtotime
A bit like this, I'd say :
$timestamp = strtotime($date_from_db);
echo date('d/m/Y', $timestamp);
But this will only work for dates between 1970 and 2038, as timestamps are stored as 32 bits integers, counting from 1970-01-01.
In MySQL, I suppose the date_format
function would do the trick.
For example :
mysql> select date_format(curdate(), '%d/%m/%Y');
+------------------------------------+
| date_format(curdate(), '%d/%m/%Y') |
+------------------------------------+
| 19/03/2010 |
+------------------------------------+
1 row in set (0.03 sec)
And, for the sake of completness, another solution, in PHP, that doesn't suffer from the limitation of 1970-2038 would be to use the DateTime
class, and, especially :
DateTime::__construct
to parse the date returned by the DBDateTime::format
to format the date to whatever format you want.For example, this portion of code :
$date = new DateTime('2010-03-19');
echo $date->format('d/m/Y');
would get you this output :
19/03/2010
Just use the Mysql built in function DATE_FORMAT()
SELECT DATE_FORMAT(some_date_field, "Y/m/d");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With