MySQL Date/Time last_day() Function
The last_day() is a MySQL date/time function that accepts date or datetime value only. It is used to get the last day of the given month for the input date. If we provide an invalid input date or datetime, it always returns a NULL value.
Syntax
The following is the syntax used to return the last date of the given month.
Parameter Explanation
Date: The last_day function accepts only one argument, either date or datetime, to get the last day date.
Return Value
This function returns the last day of the month for a given valid date argument. If the argument is invalid, we will get a NULL value.
MySQL last_day() Function Examples
Let us understand how to use the last_day() function in MySQL with the help of various examples.
Example 1
The below statement is a simple example of this function that returns the last day of the October month:
See the below output image:
Example 2
If we want to get the last date of the month using datetime format, we can use the last_day() function in the following way:
See the below output image:
Example 3
The last_day() function can also be used to get the last day of the current month. We can do this by combining the last_day() function with the NOW() or CURDATE() function like the below statements:
See the below output image:
Example 4
The last_day() function can also be used to get the last day of the next month. We can do this by adding one month to the current date and then pass the result in the last_day() function. See the below statement:
See the below output image:
Example 5
MySQL does not provide a function to get the first day of an input date. However, we can get the first day of the given date with the help of a last_day() function. We can do this using these points:
- Get the month’s last day of a given date.
- Then, add one day to get the next month’s first date using the date_add() function.
- Finally, subtract one month from the resultant result to return the month’s first day of the given date.
The below statement explains how to get the first day of the month of the given date.
See the below output image: