MySQL Date Functions

Dates are stored in the format YYYY-MM-DD. These functions help to read and calculate dates.

SELECT NOW(), CURDATE(), CURTIME();

NOW() gives the current date and time, CURDATE() only the date, and CURTIME() only the time. The result is different every moment.


Functions with a fixed date

SELECT
  YEAR('2025-01-15')                       AS y,
  MONTHNAME('2025-01-15')                  AS month_name,
  DAYNAME('2025-01-15')                    AS day_name,
  DATE_FORMAT('2025-01-15', '%d/%m/%Y')    AS formatted,
  DATEDIFF('2025-01-31', '2025-01-15')     AS days_between,
  DATE_ADD('2025-01-15', INTERVAL 10 DAY)  AS plus_ten_days,
  DATE_SUB('2025-01-15', INTERVAL 1 MONTH) AS minus_one_month;
Result
y month_name day_name formatted days_between plus_ten_days minus_one_month
2025 January Wednesday 15/01/2025 16 2025-01-25 2024-12-15

FunctionUse
NOW(), CURDATE()Current date and time
YEAR(), MONTH(), DAY()Parts of a date
DATE_FORMAT(date, format)Shows the date in your format
DATEDIFF(a, b)Days between two dates (a – b)
DATE_ADD(), DATE_SUB()Add or subtract a time
TIMESTAMPDIFF(unit, a, b)Difference in years, months, hours and more

Format codes of DATE_FORMAT

CodeMeaningExample
%dDay of the month15
%mMonth number01
%MMonth nameJanuary
%YYear, 4 digits2025
%H:%i:%sHours, minutes, seconds10:30:00
-- orders of the last 7 days
SELECT * FROM orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);
Note: Store dates in DATE or DATETIME columns, and format them only when you show them. See MySQL Data Types.

Summary

  • NOW() and CURDATE() give the current date.
  • Use DATE_FORMAT to show, DATEDIFF and DATE_ADD to calculate.
  • Next: Transactions.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.