How to use the MySQL LAST_DAY() function

MySQL LAST_DAY() is a function that returns the last day of the month for a given date or datetime value. It can be used to find the end date of a period, such as a month, quarter, or year.

Posted on

MySQL LAST_DAY() is a function that returns the last day of the month for a given date or datetime value. It can be used to find the end date of a period, such as a month, quarter, or year. The function takes one argument: the date or datetime value. The return value is a date value that represents the last day of the month for the input date. The function returns NULL if the input date is invalid or NULL.

Syntax

The syntax of the function is:

LAST_DAY(date_or_datetime)

The parameter is:

  • date_or_datetime: The date or datetime value to get the last day of the month from. It must be a valid date or datetime value, or a string in a valid date or datetime format.

Examples

Some examples of using the function are:

  • To get the last day of the current month, use:

    SELECT LAST_DAY(CURDATE());
    

    The result is:

    2023-11-30
    

    This means that the last day of the current month is November 30, 2023.

  • To get the last day of the previous month, use:

    SELECT LAST_DAY(CURDATE() - INTERVAL 1 MONTH);
    

    The result is:

    2023-10-31
    

    This means that the last day of the previous month is October 31, 2023.

  • To get the last day of the next month, use:

    SELECT LAST_DAY(CURDATE() + INTERVAL 1 MONTH);
    

    The result is:

    2023-12-31
    

    This means that the last day of the next month is December 31, 2023.

  • To get the last day of a specific month and year, use:

    SELECT LAST_DAY('2023-02-01');
    

    The result is:

    2023-02-28
    

    This means that the last day of February 2023 is February 28, 2023.

  • To get the last day of a leap year, use:

    SELECT LAST_DAY('2024-02-01');
    

    The result is:

    2024-02-29
    

    This means that the last day of February 2024 is February 29, 2024.

Similar Functions

Some similar functions to LAST_DAY() are:

  • DAY(): This function returns the day of the month for a given date or datetime value, from 1 to 31.
  • DAYOFMONTH(): This function is equivalent to the DAY() function. It returns the day of the month for a given date or datetime value, from 1 to 31.
  • DAYOFWEEK(): This function returns the day of the week for a given date or datetime value, from 1 (Sunday) to 7 (Saturday).
  • DAYOFYEAR(): This function returns the day of the year for a given date or datetime value, from 1 to 366.