简体   繁体   English

如何计算与当前日期和另一个日期的差是否等于或减去几天

[英]How to calculate if the difference from current date and another date is equal or minus of a number of days

I use this query to calculate if the current date minus another date is minus or equal an amount of days. 我使用此查询来计算当前日期减去另一个日期是否为负或等于天数。 Unfortunately this query only works if the calculation of days is inside the same month. 不幸的是,该查询仅在天数的计算在同一个月内时才起作用。 Let's take for example these datas: 让我们以这些数据为例:

current_date is: 30/08/2019 and another day is: 27/08/2019 minus or equal 3, the query works but if the current date is, for example, 01/09/2019 it doesn't work as it returns an empty list. current_date是:30/08/2019,另一天是:27/08/2019减去3或等于3,该查询有效,但是如果当前日期为例如01/09/2019,则该查询将不起作用,因为它将返回一个空列表。

This is the query I use: 这是我使用的查询:

SELECT * FROM condominio WHERE (CURRENT_DATE - condominio.revisione) <= 5

The date are store inside the column in this format: "yyyy-mm-dd" so I think it is correct. 日期以以下格式存储在列中:“ yyyy-mm-dd”,所以我认为这是正确的。 I need to put some other data togheter with current_date to have the right values returned from the query?. 我需要将其他一些数据与current_date一起使用,以使查询返回正确的值?

该查询可以为您提供帮助。

SELECT * FROM condominio AS a WHERE DATEDIFF( CURRENT_DATE, a.revisione ) <= 5
(CURRENT_DATE - condominio.revisione) <= 5

is equivalent to 相当于

CURRENT_DATE <= 5 + condominio.revisione

or 要么

CURRENT_DATE - 5 <= condominio.revisione 

and that can be expressed as 可以表示为

SELECT *
FROM condominio
WHERE condominio.revisione >= CURRENT_DATE - INTERVAL 5 DAY

If you have an index on revisione , this will also be faster than using DATEDIFF() , because an index can't be used, if the indexed column is wrapped into a function call. 如果您在revisione上具有索引,这也将比使用DATEDIFF()更快,因为如果将索引列包装到函数调用中,则无法使用索引。

try this: 尝试这个:

SELECT DATEDIFF(DATE_FORMAT(STR_TO_DATE('27/08/2018', '%d/%m/%Y'), '%Y/%m/%d') ,DATE_FORMAT(STR_TO_DATE('30/08/2018', '%d/%m/%Y'), '%Y/%m/%d') ) AS 'Date'

this function return the diff between the date. 此函数返回日期之间的差异。

good lock! 好锁!

This is the right code for my goal: 这是实现我目标的正确代码:

SELECT * FROM condominio WHERE TIMESTAMPDIFF(DAY,NOW(), DATE_ADD(revisione, INTERVAL 1 YEAR)) <= 30;

Hope it can help someone else now or in the future :-) 希望它可以现在或将来对别人有所帮助:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM