MYSQL Tutorial



MySQL DATES


MySQL Date & Time Functions

MySQL provides built-in functions to work with dates and timesโ€”retrieving the current date/time, formatting, extracting parts, and calculating differences.

Common Functions

Function Description Example
CURDATE() Returns current date SELECT CURDATE();
NOW() Returns current date & time SELECT NOW();
DATE_FORMAT() Formats date/time by pattern SELECT DATE_FORMAT(NOW(), '%Y-%m-%d');
DATEDIFF() Difference in days between dates SELECT DATEDIFF('2025-06-10','2025-06-01');
DATE_ADD() Add interval to date SELECT DATE_ADD(CURDATE(), INTERVAL 7 DAY);
DATE_SUB() Subtract interval from date SELECT DATE_SUB(NOW(), INTERVAL 1 MONTH);
YEAR()/MONTH()/DAY() Extract year, month, or day SELECT YEAR(order_date) FROM orders;

Example Usage

-- Show orders from last 30 days
SELECT * FROM orders
WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);

-- Format created_at as 'DD Month YYYY'
SELECT DATE_FORMAT(created_at, '%d %M %Y') AS formatted_date
FROM posts;

-- Calculate days between two dates
SELECT DATEDIFF(shipped_date, order_date) AS days_to_ship
FROM orders;
  

Tips & Best Practices

  • Store dates in DATE or DATETIME types, not strings.
  • Use indexes on date columns for faster range queries.
  • Be mindful of time zones; use UTC_TIMESTAMP() if needed.
  • Combine DATE_FORMAT() with locale-specific patterns for reports.

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review