Home >Database >Mysql Tutorial >Change date format (in database or output) to dd/mm/yyyy in PHP MySQL?

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

WBOY
WBOYforward
2023-08-28 10:01:011538browse

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

date(d/m/Y,yourDateTimeVariable);

In PHP, use strtodate() to convert a string to a date. This is the PHP code for formatting date time -

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

Code screenshot is below -

在 PHP MySQL 中将日期格式(在数据库或输出中)更改为 dd/mm/yyyy?

Below is the output -

12/01/2019

You This can be achieved with the help of date_format() function in MySQL. 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)

Use insert command to insert some records in the table. 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)

Use the select statement to display all records in the table. 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)

Now let us change the date format (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)

The above is the detailed content of Change date format (in database or output) to dd/mm/yyyy in PHP MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete