[英]Calculating time difference between 2 dates in minutes
我的 MySQL 數據庫中有一個時間戳字段,該字段映射到我的 bean 中的DATE
數據類型。 現在我想要一個查詢,通過它我可以獲取數據庫中當前時間戳與存儲在數據庫中的時間戳之間的差異大於 20 分鍾的所有記錄。
我該怎么做?
我想要的是:
SELECT * FROM MyTab T WHERE T.runTime - now > 20 minutes
是否有任何 MySQL 功能,或在 SQL 中執行此操作的任何方式?
我想你可以使用TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)類似的東西
select * from MyTab T where
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);
我在今天和數據庫日期使用下面的代碼。
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
根據文檔,第一個參數可以是以下任何一個:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
試試這個:
select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()
注意:如果您使用 MySQL DateTime 格式,這應該可以工作。 如果您使用的是 Unix 時間戳(整數),那么它會更容易:
select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60
UNIX_TIMESTAMP() 函數返回您當前的 Unix 時間戳。
你可以試試這個:
SELECT * FROM MyTab T WHERE CURRENT_TIMESTAMP() > T.runTime + INTERVAL 20 MINUTE;
CURRENT_TIMESTAMP() 是 function 並返回當前日期和時間。 此 function 工作於 MySQL 4.0
如果您的 MySql 版本早於 5.6,則您沒有 TIMESTAMPDIFF。 所以,我寫了我自己的 MySql function 來做到這一點。 接受 %i 或 %m 分鍾和 %h 小時。 你可以擴展它。
使用示例:
SELECT MYTSDIFF('2001-01-01 10:44:32', '2001-01-01 09:50:00', '%h')
這里是 function。 享受:
DROP FUNCTION IF EXISTS MYTSDIFF;
DELIMITER $$
CREATE FUNCTION `MYTSDIFF`( date1 timestamp, date2 timestamp, fmt varchar(20))
returns varchar(20) DETERMINISTIC
BEGIN
declare secs smallint(2);
declare mins smallint(2);
declare hours int;
declare total real default 0;
declare str_total varchar(20);
select cast( time_format( timediff(date1, date2), '%s') as signed) into secs;
select cast( time_format( timediff(date1, date2), '%i') as signed) into mins;
select cast( time_format( timediff(date1, date2), '%H') as signed) into hours;
set total = hours * 3600 + mins * 60 + secs;
set fmt = LOWER( fmt);
if fmt = '%m' or fmt = '%i' then
set total = total / 60;
elseif fmt = '%h' then
set total = total / 3600;
else
/* Do nothing, %s is the default: */
set total = total + 0;
end if;
select cast( total as char(20)) into str_total;
return str_total;
END$$
DELIMITER ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.