✏️ Explanatory Question

What are date and time functions in MySQL?

👁 9 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

30

What are date and time functions in MySQL?

Level: Intermediate — Vital for reporting, scheduling, and any time-based filtering or calculations.

Date and time functions let you retrieve the current date/time, extract parts of a date, perform date arithmetic, and format dates for display.

Common Date & Time Functions

  • NOW() / CURRENT_TIMESTAMP: Returns current date and time.
  • CURDATE() / CURTIME(): Returns current date only / time only.
  • YEAR(), MONTH(), DAY(), HOUR(): Extract a specific part from a date.
  • DATE_ADD() / DATE_SUB(): Add or subtract an interval from a date.
  • DATEDIFF() / TIMESTAMPDIFF(): Find the difference between two dates.
  • DATE_FORMAT(): Formats a date into a custom readable string.
  • DAYNAME() / MONTHNAME(): Returns the name of the day / month.
Key point: Use DATE_ADD()/DATE_SUB() with the INTERVAL keyword (e.g., INTERVAL 7 DAY) for date math — never manually add numbers, as that ignores calendar rules like month lengths and leap years.

Quick Reference with Examples

Function Example Result (sample)
NOW() NOW() 2026-08-02 13:05:00
CURDATE() CURDATE() 2026-08-02
YEAR() YEAR('2026-08-02') 2026
DATE_ADD() DATE_ADD('2026-08-02', INTERVAL 7 DAY) 2026-08-09
DATEDIFF() DATEDIFF('2026-08-10','2026-08-02') 8
DATE_FORMAT() DATE_FORMAT(NOW(), '%d-%m-%Y') 02-08-2026

Quick Example

-- Current date and time
SELECT NOW(), CURDATE(), CURTIME();

-- Orders placed in the last 30 days
SELECT * FROM orders
WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);

-- Extract year and month for grouping
SELECT YEAR(order_date) AS yr, MONTH(order_date) AS mth,
       COUNT(*) AS total
FROM orders
GROUP BY yr, mth;

-- Calculate employee age in years
SELECT name,
       TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) AS age
FROM employees;

-- Format a date for display
SELECT DATE_FORMAT(NOW(), '%W, %d %M %Y') AS pretty_date;
-- e.g., 'Sunday, 02 August 2026'
Interviewer tip: Group them by task — get current (NOW/CURDATE), extract parts (YEAR/MONTH), do math (DATE_ADD/DATEDIFF), and format (DATE_FORMAT). Mention INTERVAL for safe date arithmetic.