Home » Mysql » How to part DATE and TIME from DATETIME in MySQL

How to part DATE and TIME from DATETIME in MySQL

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am storing a DATETIME field in a Table. After Storing the value its come like
2012-09-09 06:57:12 .

For storing I am using the syntax:

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

Now My Question is, While Fetching the data, How can get both date and time separate, using the single MySQL query.

Date like 2012-09-09 and time like 06:57:12.

Answers:

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

Questions:
Answers:

per the mysql documentation, the DATE() function will pull the date part of a datetime feild, and TIME() for the time portion. so I would try:

select DATE(dateTimeFeild) as Date, TIME(dateTimeFeild) as Time, col2, col3, FROM Table1 ...

Questions:
Answers:

Try:

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

Questions:
Answers:

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

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