Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql CURDATE() -1

Tags:

date

mysql

Please, I don't understand why this command returns 00 April.

Today is 1st April 2015, and executing:

mysql> SELECT CURDATE() -1;

it returns:

| 20150400 |

+--------------+

Why CURDATE-1 doesn't return 31st March?,

00 April is an error, please it would be great if somebody could explain it.

Next, on 2nd April it works well, also for the rest of the days within the month:

mysql>

select CURDATE() -1;

|     20150401 |

This function seems is not able to operate with +x / -x out of the current month scope.

This should be highlighted in the reference guide.

BTW, I'vereplaced it with this new function:

 SELECT SUBDATE(CURDATE(),1)

Thanks.

like image 216
rheras Avatar asked Apr 02 '15 09:04

rheras


People also ask

What is MySQL Curdate?

MySQL CURDATE() Function The CURDATE() function returns the current date. Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric). Note: This function equals the CURRENT_DATE() function.

What is the purpose of Curdate () function?

CURDATE() function : This function in MySQL is used to return the current date. The date is returned to the format of “YYYY-MM-DD” (string) or as YYYYMMDD (numeric). This function equals the CURRENT_DATE() function.

What is the use of Curdate () and Sysdate ()?

MySQL Date and Time Operations SYSDATE(), NOW(), CURDATE() SELECT NOW(); This function is a synonym for SYSDATE() . SELECT CURDATE(); This function returns the current date, without any time, as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.

What is the difference between Curdate and now in MySQL?

What is the difference between MySQL NOW() and CURDATE() function? As the name suggests CURDATE() function will return the current date. In simple words, we can say that it would return only the date not time. In contrast, NOW() function will return current date and time.


2 Answers

You need to use CURDATE() - INTERVAL 1 DAY.

What are you doing with CURDATE() - 1, is treating the result of CURDATE() as an integer, not a date.

So on April 1st, CURDATE() - 1 = 20150401 - 1 = 20150400, which is clearly an invalid date.

MySQL can't intuit this for you, because with -1 it doesn't know if you mean one less day, one less month, one less year, etc.

Using MySQL's date intervals as above is the correct way to do it.

like image 166
pala_ Avatar answered Sep 20 '22 13:09

pala_


You can use:

SELECT SUBDATE(CURDATE(), 1);

or

SELECT CURDATE() - INTERVAL 1 DAY;

or

SELECT SUBDATE(CURDATE(), INTERVAL 1 DAY);

or

SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY);
like image 28
simhumileco Avatar answered Sep 20 '22 13:09

simhumileco