如何在 MySQL 中将 DATE 和 TIME 与 DATETIME 分开?

我在一个表中存储了一个 DATETIME字段,每个值看起来像这样:

2012年09月09日06:57:12

我正在使用这样的语法:

date("Y-m-d H:i:s");

现在我的问题是,在获取数据的同时,如何使用一个 MySQL 查询同时获取日期和时间 分开

日期像“ 2012-09-09”和时间像“ 06:57:12”。

166570 次浏览

You can achieve that using DATE_FORMAT() (click the link for more other formats)

SELECT DATE_FORMAT(colName, '%Y-%m-%d') DATEONLY,
DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY

SQLFiddle Demo

Try:

SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`

Per the MySQL documentation, the DATE() function will pull the date part of a datetime field, and TIME() for the time portion.

So I would try the following:

SELECT DATE(dateTimeField) as Date,
TIME(dateTimeField) as Time
FROM Table1;

For only date use
date("Y-m-d");

and for only time use
date("H:i:s");

Simply,
SELECT TIME(column_name), DATE(column_name)

An easy way would be:

For date:

SELECT DATE(column_name) as mydate

For time:

SELECT DATE(column_name) as mytime