T
T
Talyan2020-05-29 10:41:36
MySQL
Talyan, 2020-05-29 10:41:36

How to compare dates in MySQL?

I completely forgot what and how. We need your help, comrades.

I have a range of start dates for calls at the input:
start = 05/26/2020
end = 05/27/2020

in the database in the CDR table there is a start field in the datetmie format,

I do this:

SELECT * FROM crd WHERE start BETWEEN STR_TO_DATE(:start, '%d.%m.%Y') AND STR_TO_DATE(:end, '%d.%m.%Y')


but it throws an empty result.
I looked at the logs, and there MySQL does this: Issues 05/26/2020 and Issues 2020-05-26 23:50:22 Therefore, there is no selection? How is it correct for me to check if the value of the `start` field with the DATETIME type is in the date range of the 05/26/2020 and 05/27/2020 format, not using the Hindu code. With the use of between perhaps? As an option, I thought of writing shit code that in PHP converts the initial date of the range from 05/26/2020 to "2020-05-26 00:00:00" and the end date to "2020-05-27 23:59:59" and then compare , but mine is some kind of game.
SELECT STR_TO_DATE('26.05.2020', '%d.%m.%Y');


SELECT start FROM crd;



Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2020-05-29
@flapflapjack

For a correct comparison, all dates must be in YYYY-MM-DD format.
Dates are compared as strings, so if you write BETWEEN '5/26/2020' AND '5/27/2020', both '6/26/1800' and '4/27/5100' will fall into this range.

T
ThunderCat, 2020-05-29
@ThunderCat

As an option, I thought of writing shit code that in PHP converts the initial date of the range from 05/26/2020 to "2020-05-26 00:00:00" and the end date to "2020-05-27 23:59:59" and then compare , but mine is some kind of game.
That is, in your opinion, converting ALL table rows for comparison to a format NOT SUPPORTED by the database interface is ok, and bringing 2 values ​​​​to the standard is not comme il faut ...
Pay attention to the answer Rsa97 , Dates are compared as strings , so the comparison goes exactly in this format, from year to date. Your transformation makes the lines inverted in meaning, that is, sorting is by the date of the day, the year "as if it is not taken into account at all."

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question