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

MySQLMySQLi Database

You can change the date format in PHP using date() fucntion. The syntax is as follows −

date(d/m/Y,yourDateTimeVariable);

In PHP, convert string to date using strtodate(). Here is the PHP code used to format the datetime −

$LogintDate = strtotime('2019-01-12');
echo date('d/m/Y', $LogintDate);

The snapshot of code is as follows −

The following is the output −

12/01/2019

You can achieve in MySQL with the help of date_format() function. The syntax is as follows −

SELECT DATE_FORMAT(yourColumnName,’%d/%m/%Y’) as anyVariableName FROM yourTableName;

To understand the above syntax, let us create a table −

mysql> create table Date_FormatDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> LoginDate datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into Date_FormatDemo(LoginDate) values(curdate());
Query OK, 1 row affected (0.17 sec)

mysql> insert into Date_FormatDemo(LoginDate) values(now());
Query OK, 1 row affected (0.27 sec)

mysql> insert into Date_FormatDemo(LoginDate) values('2019-11-12');
Query OK, 1 row affected (0.11 sec)

mysql> insert into
Date_FormatDemo(LoginDate) values(date_add(now(),interval 2 day));
Query OK, 1 row affected (0.13 sec)

mysql> insert into Date_FormatDemo(LoginDate) values(date_add(curdate(),interval -2 day));
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from Date_FormatDemo;

The following is the output −

+----+---------------------+
| Id | LoginDate           |
+----+---------------------+
| 1 | 2019-01-12 00:00:00 |
| 2 | 2019-01-12 22:53:53 |
| 3 | 2019-11-12 00:00:00 |
| 4 | 2019-01-14 22:54:27 |
| 5 | 2019-01-10 00:00:00 |
+----+---------------------+
5 rows in set (0.00 sec)

Let us now change the date format in dd/mm/yyyy. The query is as follows −

mysql> select date_format(LoginDate,'%d/%m/%Y') as DateFormat from Date_FormatDemo;

The following is the output −

+------------+
| DateFormat |
+------------+
| 12/01/2019 |
| 12/01/2019 |
| 12/11/2019 |
| 14/01/2019 |
| 10/01/2019 |
+------------+
5 rows in set (0.00 sec)
raja
Published on 01-Feb-2019 15:28:03
Advertisements