The TIMEDIFF() function in MySQL is used to calculate the difference between two time or datetime expressions. It returns the difference as a TIME value.
Syntax:
TIMEDIFF(time1, time2)
- time1: The first time/datetime value.
- time2: The second time/datetime value.
Return Value:
The return value is the difference between time1 and time2 in the format HH:MM:SS. If time1 is greater than time2, the result will be positive; otherwise, it will be negative.
Example Usage:
- Simple Time Difference:
SELECT TIMEDIFF('2024-12-23 14:30:00', '2024-12-23 13:15:00');
Output: 01:15:00 (1 hour and 15 minutes)
- Time Difference with Only Time:
SELECT TIMEDIFF('14:30:00', '13:15:00');
Output: 01:15:00 (1 hour and 15 minutes)
- Negative Time Difference:
SELECT TIMEDIFF('12:00:00', '14:00:00');
Output: -02:00:00 (2 hours negative)
- Using
TIMEDIFF()in a Query:
SELECT name, TIMEDIFF(end_time, start_time) AS duration
FROM events;
This will calculate the time difference between end_time and start_time for each event and display it as duration.
Notes:
- If you use
DATETIMEorTIMESTAMPvalues, theTIMEDIFF()function only considers the time part and ignores the date portion. TIMEDIFF()only works with values of theTIME,DATETIME, orTIMESTAMPdata types.
Let me know if you'd like more specific examples or explanations!
No comments:
Post a Comment