SQL Date and Time Functions (GETDATE, DATEADD, DATEDIFF, FORMAT, ...)
πΉ Why Learn Date & Time Functions?
Reporting, scheduling, and analytics depend on accurate timestamps. SQL offers portable functions to get the current time, add or subtract intervals, compute differences, format output, and extract components.
βοΈ Common Date & Time Functions
| Function |
Purpose |
Example |
Result |
| GETDATE() | Current date & time (SQL Server) | SELECT GETDATE(); | 2025-10-24 10:15:30 |
| CURRENT_DATE | Current date only | SELECT CURRENT_DATE; | 2025-10-24 |
| DATEADD() | Add/subtract intervals | DATEADD(DAY, 5, '2025-10-20') | 2025-10-25 |
| DATEDIFF() | Difference between dates | DATEDIFF(DAY, '2025-10-01', '2025-10-24') | 23 |
| DATEPART() | Extract part of date | DATEPART(MONTH, GETDATE()) | 10 |
| FORMAT() | Format output | FORMAT(GETDATE(), 'dd-MMM-yyyy') | 24-Oct-2025 |
| NOW() | Current timestamp (MySQL/PostgreSQL) | SELECT NOW(); | 2025-10-24 10:15:30 |
| EOMONTH() | End of month | EOMONTH(GETDATE()) | 2025-10-31 |
π§ Example 1 β Current Date and Time
SELECT
GETDATE() AS current_datetime,
CURRENT_TIMESTAMP AS current_timestamp,
NOW() AS mysql_now;
π§ Example 2 β Add or Subtract Dates
SELECT
GETDATE() AS today,
DATEADD(DAY, 7, GETDATE()) AS next_week,
DATEADD(MONTH, -1, GETDATE()) AS last_month;
π§ Example 3 β Differences Between Dates
SELECT
DATEDIFF(DAY, '2025-10-01', '2025-10-24') AS days_diff,
DATEDIFF(MONTH, '2025-01-01', '2025-10-24') AS months_diff,
DATEDIFF(YEAR, '2020-10-24', '2025-10-24') AS years_diff;
π§ Example 4 β Extract Components
SELECT
DATEPART(YEAR, GETDATE()) AS year_part,
DATEPART(MONTH, GETDATE()) AS month_part,
DATEPART(DAY, GETDATE()) AS day_part;
π§ Example 5 β Format Dates
SELECT
FORMAT(GETDATE(), 'yyyy-MM-dd') AS iso_format,
FORMAT(GETDATE(), 'dd-MMM-yyyy') AS readable_format,
FORMAT(GETDATE(), 'hh:mm tt') AS time_format;
π§ Example 6 β Filter by Date Range
SELECT *
FROM orders
WHERE order_date BETWEEN '2025-10-01' AND '2025-10-24';
π§ Example 7 β Start and End of Month
SELECT
DATEADD(DAY, -DAY(GETDATE()) + 1, GETDATE()) AS start_of_month,
EOMONTH(GETDATE()) AS end_of_month;
βοΈ Bonus β Time Differences in Smaller Units
SELECT
DATEDIFF(HOUR, '2025-10-24 08:00:00', '2025-10-24 14:30:00') AS hours_diff,
DATEDIFF(MINUTE, '2025-10-24 08:00:00', '2025-10-24 14:30:00') AS minutes_diff;
βοΈ Summary Cheat Sheet
| Task |
Function |
| Get current timestamp | GETDATE(), NOW() |
| Add/subtract time | DATEADD() |
| Calculate differences | DATEDIFF() |
| Extract components | DATEPART(), EXTRACT() |
| Format output | FORMAT() |
| Find month end | EOMONTH() |
π‘ Interview Soundbite
βGETDATE fetches the current timestamp, DATEADD and DATEDIFF manage intervals, and FORMAT or DATEPART shape the output for reports.β