MySQL TIMESTAMPDIFF() Function

MySQL TIMESTAMPDIFF() function; Through this tutorial, i am going to show you how to find or calculate difference between two dates or datetimes using MySQL timestampdiff() function.

MySQL TIMESTAMPDIFF() Function

The MySQL TIMESTAMPDIFF () function is used to calculate the difference between two date or DateTime expressions.

Syntax of MySQL TIMESTAMPDIFF() Function

The syntax is MySQL timestampdiff(); as follows:

TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)

This function reduces datetime_expr1 from datetime_expr2 and returns results in units. The result is returned as an integer.

And the unit an argument can be any of the following:

  • MICROSECOND
  •  SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR

Example 1 – Compare Two Dates Using MySQL TIMESTAMPDIFF() Function

To compare the two dates and return the differences between them in days using timestampdiff() function; as follows:

  SELECT 
  TIMESTAMPDIFF(DAY,'2022-02-01','2022-02-21')
  AS 'Difference in Days';

Output-1

+--------------------+
| Difference in Days |
+--------------------+
|                 20 |
+--------------------+

Example 2 – MySQL TIMESTAMPDIFF() Function

To compare the values ​​of the previous examples, except by leaving here, we return the difference in hours; as follows:

  SELECT 
  TIMESTAMPDIFF(HOUR,'2022-02-01','2022-02-21')
  AS 'Difference in Hours';

Output-2

+---------------------+
| Difference in Hours |
+---------------------+
|                 480 |
+---------------------+

Example 3 – MySQL TIMESTAMPDIFF() Function

To compare two dates and returns a difference in minutes using the timestampdiff() function; as follows:

  SELECT 
  TIMESTAMPDIFF(MINUTE,'2022-02-01 10:30:27','2022-02-01 10:45:27')
  AS 'Difference in Minutes';

Output-3

+-----------------------+
| Difference in Minutes |
+-----------------------+
|                    15 |
+-----------------------+

Example 4 – MySQL TIMESTAMPDIFF() Function

To compare two dates and first date/time argument is greater than the second, the result would be a negative integer using the timestampdiff() function; as follows:

  SELECT 
  TIMESTAMPDIFF(DAY,'2022-02-21','2022-02-01')
  AS 'Difference in Days';

Output-4

+--------------------+
| Difference in Days |
+--------------------+
|                -20 |
+--------------------+

Conclusion

MySQL TIMESTAMPDIFF() Function tutorial, you have learned how to use MySQL TIMESTAMPDIFF() function with various examples.

Leave a Comment