Home > Database > Mysql Tutorial > How Can I Calculate Date Differences in MySQL Using TIMEDIFF() and TIMESTAMPDIFF()?

How Can I Calculate Date Differences in MySQL Using TIMEDIFF() and TIMESTAMPDIFF()?

Patricia Arquette
Release: 2025-01-10 21:26:47
Original
696 people have browsed it

How Can I Calculate Date Differences in MySQL Using TIMEDIFF() and TIMESTAMPDIFF()?

MySQL date difference calculation

Calculating the time difference between two dates is a common task in data processing and analysis. MySQL provides an easy way to achieve this functionality.

Syntax and return values:

MySQL uses the TIMEDIFF() and TIMESTAMPDIFF() functions to calculate date differences. TIMEDIFF() Returns the difference between two dates, expressed in HH:MM:SS format. TIMESTAMPDIFF() Allows you to specify the time unit for the result, such as seconds or milliseconds.

Usage:

To calculate the second difference, use the following syntax:

<code class="language-sql">SELECT TIMESTAMPDIFF(SECOND, 开始日期, 结束日期);</code>
Copy after login

To get the millisecond difference, use:

<code class="language-sql">SELECT TIMESTAMPDIFF(MICROSECOND, 开始日期, 结束日期) / 1000;</code>
Copy after login

Example:

Suppose you need to calculate the difference between '2007-12-31 10:02:00' and '2007-12-30 12:01:01'.

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

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

As shown above, TIMESTAMPDIFF() provides the difference in seconds, while TIMEDIFF() displays the difference in hours, minutes, and seconds.

The above is the detailed content of How Can I Calculate Date Differences in MySQL Using TIMEDIFF() and TIMESTAMPDIFF()?. 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