计算 MySQL 中两个日期时间之间的差异

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

Calculate difference between two datetimes in MySQL

mysql

提问by Devesh Agrawal

I am storing the last login time in MySQL in, datetime-type filed. When users logs in, I want to get the difference between the last login time and the current time (which I get using NOW()).

我将上次登录时间存储在 MySQL 中,datetime-type 归档。当用户登录时,我想获得上次登录时间和当前时间(我使用的时间NOW())之间的差异。

How can I calculate it?

我该如何计算?

回答by FSP

USE TIMESTAMPDIFFMySQL function. For example, you can use:

使用TIMESTAMPDIFFMySQL 函数。例如,您可以使用:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFFfunction would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

在您的情况下,TIMSTAMPDIFF函数的第三个参数将是当前登录时间 ( NOW())。第二个参数是上次登录时间,该时间已经在数据库中。

回答by ingconti

my two cents about logic:

我对逻辑的两分钱:

syntax is "old date" - :"new date", so:

语法是“旧日期” - :“新日期”,所以:

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')

gives 30,

给 30,

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')

gives: -40

给:-40

回答by Adi

If your start and end datetimes are on different days use TIMEDIFF.

如果您的开始和结束日期时间在不同的日子,请使用 TIMEDIFF。

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

如果 datetime1 > datetime2 那么

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

给: 24:01:00

and datetime1 < datetime2

和日期时间 1 < 日期时间 2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

给出:-24:01:00