简体   繁体   中英

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.

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. I need to put some other data togheter with current_date to have the right values returned from the query?.

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

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.

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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