如何从 MySQL 中的日期时间中减去小时数?

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

How to subtract hours from a datetime in MySQL?

mysqldatetimegmt

提问by Lucas Famelli

I get a datetime field, that's currently in the query as:

我得到一个日期时间字段,它当前在查询中为:

SELECT DATE_FORMAT(x.date_entered, '%Y-%m-%d') AS date FROM x ORDER BY date ASC

What I want to do is to subtract 3 hours from that date (GMT issues), but I can't do it in PHP as PHP only knows the date part, not the time.

我想要做的是从那个日期减去 3 小时(GMT 问题),但我不能在 PHP 中做到这一点,因为 PHP 只知道日期部分,而不知道时间。

回答by Pekka

mySQL has DATE_SUB():

mySQL 有DATE_SUB()

SELECT DATE_SUB(column, INTERVAL 3 HOUR)....

but would it not be better to try and sort out the underlying time zone issue instead?

但是尝试解决潜在的时区问题不是更好吗?

回答by webjunkie

Assuming you have some timezone issue and know source and destination timezone, you could convert it like so

假设您有一些时区问题并且知道源时区和目标时区,您可以像这样转换它

SELECT DATE_FORMAT(CONVERT_TZ(x.date_entered, 'UTC', 'Europe/Berlin'),
                   '%Y-%m-%d') AS date
FROM x ORDER BY date ASC;