Home > Database > Mysql Tutorial > How to Calculate the Time Difference Between Two Datetimes in MySQL?

How to Calculate the Time Difference Between Two Datetimes in MySQL?

DDD
Release: 2024-12-09 04:55:14
Original
561 people have browsed it

How to Calculate the Time Difference Between Two Datetimes in MySQL?

How to Calculate the Temporal Difference Between Two Datetimes in MySQL

When maintaining user login information in MySQL's datetime data type, determining the time elapsed since a user's last login is essential. To perform this calculation, MySQL provides the TIMESTAMPDIFF function.

Query Syntax:

SELECT TIMESTAMPDIFF(<interval>, <start_datetime>, <end_datetime>)
Copy after login

Parameters:

  • : Specifies the unit of measurement for the difference, such as SECOND, MINUTE, HOUR, DAY, MONTH, or YEAR.
  • : Represents the earlier timestamp as a string or datetime value.
  • : Represents the later timestamp as a string or datetime value.

Example:

Consider a scenario where you want to calculate the difference between the last login time (last_login_time) and the current time (NOW()) in seconds. You can use the following query:

SELECT TIMESTAMPDIFF(SECOND, last_login_time, NOW())
Copy after login

Sample Result:

The query will return the difference between the last login time and the current time in seconds. For instance, if the last login time is '2023-07-25 14:50:00' and the current time is '2023-07-25 15:05:30', the result will be 870 seconds.

The above is the detailed content of How to Calculate the Time Difference Between Two Datetimes 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template