这个问题的一个很好的例子是计算生日的剩余天数
我正在使用DateDiff(CURRDATE(),"生日栏")函数,并收到天数差,这是我需要做的mod 365。
Mod 365用于在联系人昨天过生日时检索364。
DateDiff(CURRDATE(),CURRDATE()-间隔1天)=-1
MOD(-1365)=-1
:\有线!
我找到了这个问题的解决方案
MOD(MOD(负,365)+365),365)
USE `test`;
DROP procedure IF EXISTS `get_user_contacts`;
DELIMITER $$
USE `test`$$
CREATE PROCEDURE `test`.`get_user_contacts` (user_id INT(11),lim INT(11))
BEGIN
DECLARE is_user_exist INT(11);
SELECT count(*) INTO is_user_exist FROM users WHERE `users`.`id` = user_id;
IF is_user_exist =1 THEN
SELECT `contacts`.*,MOD(MOD(DATEDIFF(CURDATE(),`contacts`.`birthday` + INTERVAL (EXTRACT(YEAR FROM CURDATE())-EXTRACT(YEAR FROM `contacts`.`birthday`)) YEAR)*(-1),365)+365,365) AS DiffDate FROM contacts
LEFT JOIN contacts_users ON `contacts`.`id` = `contacts_users`.`contact_id`
LEFT JOIN users ON `contacts_users`.`user_id` = `users`.`id` LIMIT lim;
ELSE
SELECT 404 as error_number,'User not found.' as message;
END IF;
END$$
DELIMITER ;
祝你好运!
如果问题是关于"生日前几天",那么365将无法正确处理闰年。
SELECT @bd := DATE('1992-02-02'); -- for testing previous day
SELECT @bd := DATE('1992-05-02'); -- for testing future day
SELECT DATEDIFF(@bd +
INTERVAL (YEAR(CURDATE()) - YEAR(@bd)) + -- Age or Age+1
(DAYOFYEAR(@bd) < DAYOFYEAR(CURDATE())) -- +1 for earlier this year;
YEAR,
CURDATE());