MySQL DATEDIFF()
The DATEDIFF()
function returns the number of days between two dates. The order of the dates matters: DATEDIFF(date1, date2)
returns the difference as date1 - date2
.
Examples
1. Calculating the Difference Between Two Dates
SELECT DATEDIFF('2024-11-03', '2024-11-01') AS days_difference;
Code Explanation: This query returns the difference in days between '2024-11-03' and '2024-11-01', which is 2 days.
2. Using DATEDIFF with Event Dates
SELECT event_name, DATEDIFF(NOW(), event_date) AS days_since_event FROM tamil_kings_events;
Code Explanation: This query calculates the number of days since each event in the tamil_kings_events
table.
Best Practices
- Use
DATEDIFF()
for date calculations and to measure time intervals. - Ensure the date format is correct to avoid errors.
Key Takeaways
- The
DATEDIFF()
function returns the difference in days between two dates. - It is useful for calculating durations or time intervals.