MySQL 从日期和时间创建日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1318630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating DATETIME from DATE and TIME
提问by gregor
Is there way in MySQL to create DATETIME from a given attribute of type DATE and a given attribute of type TIME?
在 MySQL 中有没有办法从 DATE 类型的给定属性和 TIME 类型的给定属性创建 DATETIME?
采纳答案by Zed
datetime = CONCAT(date, ' ', time);
回答by johnson
Copied from the MySQL Documentation:
复制自 MySQL 文档:
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.
使用单个参数,此函数将日期或日期时间表达式 expr 作为日期时间值返回。使用两个参数,它将时间表达式 expr2 添加到日期或日期时间表达式 expr1 并将结果作为日期时间值返回。
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'
回答by CDuv
To get a trueDATETIME
value from your two separate DATE
and TIME
values:
要从两个独立的和值中获得真正的值:DATETIME
DATE
TIME
STR_TO_DATE(CONCAT(date, ' ', time), '%Y-%m-%d %H:%i:%s')
回答by SystemParadox
You could use ADDTIME()
:
你可以使用ADDTIME()
:
ADDTIME(CONVERT(date, DATETIME), time)
date
may be a date string or aDATE
object.time
may be a time string or aTIME
object.
date
可以是日期字符串或DATE
对象。time
可以是时间字符串或TIME
对象。
Tested in MySQL 5.5.
在 MySQL 5.5 中测试。
回答by Michael Grazebrook
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!
我同意 Muki - 一定要考虑时区和夏令时!
回答by Kalle
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.
有效,当字符串格式正确时。否则,您可以只使用 str_to_date 包含时间。
select str_to_date('12/31/2003 14:59','%m/%d/%Y %H:%i');