Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to part DATE and TIME from DATETIME in MySQL

I am storing a DATETIME field in a Table. Each value looks something like this: 2012-09-09 06:57:12 .

I am using this syntax:

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

Now my question is, while fetching the data, how can get both date and time separately, using the single MySQL query?

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

like image 685
Miss Rosy Avatar asked Sep 09 '12 07:09

Miss Rosy


People also ask

How do you display time and date in MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.

How do I get just the date from a timestamp?

You can use date(t_stamp) to get only the date part from a timestamp. Extracts the date part of the date or datetime expression expr.

How do I change datetime to date in MySQL?

Here is the query to convert from datetime to date in MySQL. mysql> select cast(ArrivalDatetime as Date) as Date from ConvertDateTimeToDate; The following is the output.


2 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

like image 82
John Woo Avatar answered Oct 09 '22 07:10

John Woo


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(dateTimeField) as Date, TIME(dateTimeField) as Time, col2, col3, FROM Table1 ... 
like image 36
Frank Thomas Avatar answered Oct 09 '22 06:10

Frank Thomas