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 |
| Function | Use |
|---|---|
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
| Code | Meaning | Example |
|---|---|---|
%d | Day of the month | 15 |
%m | Month number | 01 |
%M | Month name | January |
%Y | Year, 4 digits | 2025 |
%H:%i:%s | Hours, minutes, seconds | 10: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()andCURDATE()give the current date.- Use
DATE_FORMATto show,DATEDIFFandDATE_ADDto calculate. - Next: Transactions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |