TIMESTAMPDIFF() in MySQL 8: Get the difference between two timestamps

Updated: January 26, 2024 By: Guest Contributor Post a comment

Introduction

TIMESTAMPDIFF() is a powerful built-in function in MySQL that allows you to calculate the difference between two date or datetime expressions. Understanding how to leverage this command within MySQL 8 can significantly help you in handling time-based data, from calculating age to comparing timestamps from various events.

In this tutorial, let’s delve into the TIMESTAMPDIFF() function and how to effectively use it within MySQL 8. By the end of this post, you will have a solid foundation in using TIMESTAMPDIFF() with various levels of complexity and practical applications. Let’s get started!

Getting Started with TIMESTAMPDIFF()

SELECT TIMESTAMPDIFF({UNIT},{DATETIME_EXPR1},{DATETIME_EXPR2});

The TIMESTAMPDIFF() function accepts three parameters: the unit of time you want to calculate the difference in, the starting datetime expression and the ending datetime expression. It returns the difference as an integer. The general syntax for TIMESTAMPDIFF() is shown above.

Understanding the Parameters

  • UNIT: The unit of time to measure the difference in. It could be YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, MINUTE, or SECOND.
  • DATETIME_EXPR1 and DATETIME_EXPR2: The two dates or datetimes to compare. TIMESTAMPDIFF() calculates the difference from DATETIME_EXPR1 to DATETIME_EXPR2.

Let us see a few basic examples:

SELECT TIMESTAMPDIFF(YEAR, '2021-01-01', '2023-01-01') AS DifferenceInYears;

This query would return 2, as there is a two-year difference between the dates 2021-01-01 and 2023-01-01.

SELECT TIMESTAMPDIFF(MONTH, '2021-01-01', '2021-05-01') AS DifferenceInMonths;

The above query would return 4 for the number of months between the two dates.

Comparing Time and Dates (Basic Examples)

Here are a few basic examples that demonstrate the use of different units with the TIMESTAMPDIFF() function:

/* Days difference */
SELECT TIMESTAMPDIFF(DAY, '2023-01-01', '2023-01-31') AS DifferenceInDays;

/* Hours difference */
SELECT TIMESTAMPDIFF(HOUR, '2023-01-01 08:00:00', '2023-01-02 08:00:00') AS DifferenceInHours;

/* Minutes difference */
SELECT TIMESTAMPDIFF(MINUTE, '2023-01-01 12:00', '2023-01-01 14:30') AS DifferenceInMinutes;

These queries return 30, 24, and 150 respectively for the differences in days, hours, and minutes.

Complex Date Comparisons

As your mastery of TIMESTAMPDIFF() grows, you can begin to craft more complex queries involving various operations.

/* Working with Curdate() */
SELECT TIMESTAMPDIFF(YEAR, '1990-05-25', CURDATE()) AS Age;

/* Using nested functions */
SELECT TIMESTAMPDIFF(MONTH, DATE_ADD('2023-01-01', INTERVAL 1 MONTH), DATE_ADD('2023-01-01', INTERVAL 5 MONTH)) AS IntervalDifference;

The first example will return the number of full years since the specified birthday (‘1990-05-25’) to the current date. The second example demonstrates the use of TIMESTAMPDIFF() with nested functions such as DATE_ADD().

Advanced Applications

Moving to more advanced applications with TIMESTAMPDIFF(), here are a few examples which include extracting a report for a period, comparing time intervals from system events, or setting up triggers that calculate elapsed time.

/* Report generation for a particular period */
SELECT product_id, sales_date FROM sales
WHERE TIMESTAMPDIFF(MONTH, sales_date, NOW()) <= 6;

/* Comparing timestamps from two different tables */
SELECT a.event_name, b.user_action
FROM events_table a
JOIN user_actions b ON a.event_id = b.event_id
WHERE TIMESTAMPDIFF(SECOND, a.event_timestamp, b.action_timestamp) < 60;

The first query fetches products sold within the last 6 months, while the second query cross-examines timestamps from two different tables to compare an event timestamp with a user action timestamp, looking for ones that occurred within 60 seconds of each other.

Conclusion

To conclude, the TIMESTAMPDIFF() function in MySQL is a versatile tool for date and time arithmetic. From straightforward calculations to complex queries involving joins and nested functions, TIMESTAMPDIFF() enhances your ability to work with temporal data. Whether you’re new to TIMESTAMPDIFF() or looking to refine your usage of it, the examples provided here offer a practical approach to harnessing its potential within MySQL 8.