MySQL has the LAST_DAY(date) function that returns the date for the last day of the month:
SELECT LAST_DAY(fecha) AS ultimo_dia
FROM table
How can I get the date for the first day of the month?
MySQL has the LAST_DAY(date) function that returns the date for the last day of the month:
SELECT LAST_DAY(fecha) AS ultimo_dia
FROM table
How can I get the date for the first day of the month?
Two alternatives occur to me:
Both involve only 2 function calls. They will surely differ in efficiency based on whether the
INTERVAL
is calculated faster than theSUBDATE
.Apparently there is no function that returns the first day of the month, you should create it, and it goes something like this:
and you would use it like this
font
first day of the month
First day of the following month : it is simply the last day + 1
Source: Extracted from StacOverFlow available at https://stackoverflow.com/questions/3009896/get-the-first-and-last-date-of-next-month-in-mysql
A quick option: create a new date by concatenating the year and month of the date, and specify a 1 for the day. The code would be like this:
You could save that code in a function:
And call the function directly from the
SELECT
:Testing in my DB, I think this could work applied to a table:
Update:
It only seems to work fine if you pass it a specific record:
If you wanted to know, for example, from a table the first day of the month with respect to all records, you could add
MAX
to the query:just implement it like this:
without the need for additional functions.
I found a solution thanks to the guides mentioned above and I managed to obtain the first day of the month in the following way:
With this, what it does is that it obtains the date omitting the time, now if what you want is the date and time, then replace CURRENT_DATE with NOW().
CURRENT_DATE returns 2017-09-01, while NOW() returns: 2017-09-01 02:10:39
An example query to serve as a guide:
In itself it is more orderly since it returns the type DATE.
There is a very portable way that works for me....
Answer: 2019-08-01