MySQL 如何将日期时间转换为日期,截断时间,留下日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7527315/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:09:07  来源:igfitidea点击:

How can I convert datetime to date, truncating the times, leaving me the dates?

mysqlsql

提问by i-CONICA

I have a field that's in datetime format when date would be better and more consistent with the rest of the database, so I want to convert. The time part is all 00:00:00 anyway.

我有一个日期时间格式的字段,当日期会更好并且与数据库的其余部分更一致时,所以我想转换。无论如何,时间部分都是 00:00:00。

How can I do this in MySQL?

我怎样才能在 MySQL 中做到这一点?

Thanks.

谢谢。

回答by Bjoern

If you want this in a SELECT-Statement, just use the DATEOperator:

如果您想在SELECT-Statement 中使用它,只需使用DATE运算符:

SELECT DATE(`yourfield`) FROM `yourtable`;

If you want to change the table structurally, just change the datatype to DATE(of course only do this if this doesn't affect applications depending on this field).

如果要在结构上更改表,只需将数据类型更改为DATE(当然,只有在不影响依赖此字段的应用程序时才这样做)。

ALTER TABLE `yourtable` CHANGE `yourfield` `yourfield` DATE;

Both will eliminate the time part.

两者都将消除时间部分。

回答by Dave

Cast it as a DATE:

将其转换为 DATE:

select DATE(my_date_time)

That will truncate the time from it, leaving only the date part.

这将截断它的时间,只留下日期部分。

回答by zabusa

when using change we have to repeat the same name again for the field.now we can use MODIFYto alter the filed type.

使用更改时,我们必须再次为字段重复相同的名称。现在我们可以使用MODIFY更改字段类型。

ALTER TABLE `yourtable` MODIFY `yourfield` DATE;

ALTER TABLE `yourtable` MODIFY `yourfield` DATE;