[Solved] adddate(curdate(), -(day(curdate())-1)) and concat(last_day(curdate()),’ 23:59:59′) [closed]


DAY(CURDATE())-1 is the current day of the month, less 1. For today (Aug 15, 2013), the value would be 14. Subtract 14 days from August 15 and you have August 1. In other words, ADDDATE(CURDATE(), -(DAY(CURDATE())-1)) gives you the first day of the month.

LAST_DAY(CURDATE()) gives you the last day of the month. If you call it today it will return August 31, 2013. Append the 23:59:59 and you have the last second of the last day of the month.

In other words, if called on August 15, 2013, the values come out as 2013-08-01 and 2013-08-31 23:59:59. If this range is applied against a DATETIME value, it means “anything in the month of August 2013”.

This is actually a pretty good way to check for date/time values within a month because it avoids using a function on the MySQL column that holds the date/time. If the column has an index, the index will (probably) be used for optimization. One approach I often see is this:

WHERE DATE_FORMAT(myDateTime, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m')

This reads a little better, but it kills optimization. I’d stick with the expression you already have.

2

solved adddate(curdate(), -(day(curdate())-1)) and concat(last_day(curdate()),’ 23:59:59′) [closed]