Friday, December 20, 2024

MySQL ADDDATE() Function

 The ADDDATE() function in MySQL is used to add a specific time interval (such as days, months, or years) to a given date. This function allows you to perform date arithmetic easily.

Syntax:

ADDDATE(date, INTERVAL value unit)
  • date: The starting date to which the interval will be added.
  • value: The numeric value representing the interval (e.g., 1, 5, etc.).
  • unit: The unit of the interval (e.g., DAY, MONTH, YEAR, HOUR, etc.).

Examples:

  1. Adding Days to a Date:

    SELECT ADDDATE('2024-12-21', INTERVAL 5 DAY);
    

    This adds 5 days to '2024-12-21', resulting in '2024-12-26'.

  2. Adding Months to a Date:

    SELECT ADDDATE('2024-12-21', INTERVAL 2 MONTH);
    

    This adds 2 months to '2024-12-21', resulting in '2025-02-21'.

  3. Adding Years to a Date:

    SELECT ADDDATE('2024-12-21', INTERVAL 1 YEAR);
    

    This adds 1 year to '2024-12-21', resulting in '2025-12-21'.

  4. Adding Hours to a Date:

    SELECT ADDDATE('2024-12-21 10:00:00', INTERVAL 3 HOUR);
    

    This adds 3 hours to '2024-12-21 10:00:00', resulting in '2024-12-21 13:00:00'.

Notes:

  • If you don't specify an interval unit, MySQL assumes you are adding days.
  • The ADDDATE() function can also be used with the + operator. For example:
    SELECT '2024-12-21' + INTERVAL 5 DAY;
    

This is a flexible function to work with dates and time intervals in MySQL.

No comments:

Post a Comment