How to calculate the minutes of time difference in MySQL

Calculating the minutes difference between times is a very common need in MySQL. This article will introduce some useful functions to help you easily calculate the difference in minutes between times.

1. TIMEDIFF function

The TIMEDIFF function is one of the functions used in MySQL to calculate the time difference. Its syntax is as follows:

e1e2)

e1e2 are two time values, which can be column names or strings of time type.

Use the TIMEDIFF function to calculate the time difference between two times, and the return value is a time type. If you only need to calculate the minutes, you can use the TIME_TO_SEC function to convert the time type to seconds, and then divide the seconds by 60.

SELECT TIME_TO_SEC(TIMEDIFF('2022-01-01 12:00:00', '2022-01-01 11:30:00')) / 60;

2. TIMESTAMPDIFF function

The TIMESTAMPDIFF function is another function in MySQL that is used to calculate the time difference. Its syntax is as follows:

eat1e2)

ite1e2 is two time values, which can be column names or strings of time type.

Use the TIMESTAMPDIFF function to directly calculate the difference in minutes between two times.

SELECT TIMESTAMPDIFF(MINUTE, '2022-01-01 11:30:00', '2022-01-01 12:00:00');

3. DATEDIFF function

The DATEDIFF function is a function used in MySQL to calculate date differences, but it can also be used to calculate time differences. Its syntax is as follows:

DATEDIFF(date1, date2)

Among them, date1 and date2 are two date values, which can be column names or strings of date type.

Use the DATEDIFF function to calculate the number of days between two dates. If you need to calculate the number of minutes, you can multiply the number of days by 24 and then by 60.

SELECT DATEDIFF('2022-01-01 12:00:00', '2022-01-01 11:30:00') * 24 * 60;

This article introduces three commonly used functions in MySQL to calculate the minutes of time difference. They are TIMEDIFF, TIMESTAMPDIFF and DATEDIFF functions. Use these functions to easily calculate the minutes difference between times and improve your productivity.

Guess you like

Origin blog.csdn.net/zlfjavahome/article/details/132709159