Creating DATETIME from DATE and TIME

MysqlDatetime

Mysql Problem Overview


Is there way in MySQL to create DATETIME from a given attribute of type DATE and a given attribute of type TIME?

Mysql Solutions


Solution 1 - Mysql

Copied from the MySQL Documentation:

TIMESTAMP(expr), TIMESTAMP(expr1,expr2)

> With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value.

mysql> SELECT TIMESTAMP('2003-12-31');
    -> '2003-12-31 00:00:00'
mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');
    -> '2004-01-01 00:00:00'

Solution 2 - Mysql

To get a true DATETIME value from your two separate DATE and TIME values:

STR_TO_DATE(CONCAT(date, ' ', time), '%Y-%m-%d %H:%i:%s')

Solution 3 - Mysql

You could use ADDTIME():

ADDTIME(CONVERT(date, DATETIME), time)
  • date may be a date string or a DATE object.
  • time may be a time string or a TIME object.

Tested in MySQL 5.5.

Solution 4 - Mysql

datetime = CONCAT(date, ' ', time);

Solution 5 - Mysql

select timestamp('2003-12-31 12:00:00','12:00:00'); 

works, when the string is formatted correctly. Otherwise, you can just include the time using str_to_date.

select str_to_date('12/31/2003 14:59','%m/%d/%Y %H:%i');

Solution 6 - Mysql

Without creating and parsing strings, just add an interval to the date:

set @dt_text = '1964-05-13 15:34:05.757' ;
set @d = date(@dt_text) ;
set @t = time(@dt_text) ;
select @d, @t, @d + interval time_to_sec( @t ) second;

However this truncates the microseconds.

I agree with Muki - be sure to take account of time zones and daylight savings time!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongregorView Question on Stackoverflow
Solution 1 - MysqljohnsonView Answer on Stackoverflow
Solution 2 - MysqlCDuvView Answer on Stackoverflow
Solution 3 - MysqlSystemParadoxView Answer on Stackoverflow
Solution 4 - MysqlZedView Answer on Stackoverflow
Solution 5 - MysqlChristianView Answer on Stackoverflow
Solution 6 - MysqlMichael GrazebrookView Answer on Stackoverflow