Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change date format (in DB or output) to dd/mm/yyyy - PHP MySQL

Tags:

date

sql

php

mysql

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?

like image 985
Jess Avatar asked Mar 19 '10 19:03

Jess


People also ask

How can I get dd mm yyyy format in PHP?

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));

How do I change MySQL date format from DD MM to YYYY?

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.

How do I convert a date from one format to another in MySQL?

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.


2 Answers

In PHP, you could :

  • Transform the date to a timestamp, using strtotime
  • Format it, using date

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 DB
  • DateTime::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
like image 128
Pascal MARTIN Avatar answered Sep 19 '22 21:09

Pascal MARTIN


Just use the Mysql built in function DATE_FORMAT()

SELECT DATE_FORMAT(some_date_field, "Y/m/d");
like image 39
John Conde Avatar answered Sep 18 '22 21:09

John Conde