Creating DATETIME from DATE and TIME

Viewed 58565

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

6 Answers

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'

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.

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');
Related