Home > Database > Mysql Tutorial > How to Calculate Date and Time Differences in MySQL?

How to Calculate Date and Time Differences in MySQL?

Patricia Arquette
Release: 2025-01-10 21:31:48
Original
381 people have browsed it

How to Calculate Date and Time Differences in MySQL?

MySQL date and time difference calculation method

In database programming, calculating the difference between two date times is a very common operation. MySQL provides two main ways to achieve this functionality: TIMEDIFF and TIMESTAMPDIFF.

TIMEDIFF function

TIMEDIFF The function calculates the difference between two datetime values ​​and returns the result in HH:MM:SS format. For example:

<code class="language-sql">SELECT TIMEDIFF('2007-12-31 10:02:00', '2007-12-30 12:01:01');
-- 结果:22:00:59</code>
Copy after login

This query returns the difference between two dates, which is 22 hours, 0 minutes and 59 seconds.

TIMESTAMPDIFF function

TIMESTAMPDIFF The function calculates the difference between two dates, times, or timestamps and returns an integer representing the number of seconds or milliseconds. For example:

<code class="language-sql">SELECT TIMESTAMPDIFF(SECOND, '2007-12-30 12:01:01', '2007-12-31 10:02:00');
-- 结果:79259</code>
Copy after login

This query returns the difference in seconds between two dates, which is 79259 seconds.

How to use

Which method to choose depends on the desired output format. If you want the difference in HH:MM:SS format, use TIMEDIFF; if you want the difference in seconds or milliseconds, use TIMESTAMPDIFF.

The above is the detailed content of How to Calculate Date and Time Differences in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template