Calculating time difference between 2 dates in minutes
To find the minute difference between two dates in SQL Server, use DATEDIFF:
If you're on MySQL, utilize TIMESTAMPDIFF:
Both queries return 90 — the total minutes between those two points in time.
Selecting records based on time difference
Let's say you have a date endurance challenge, this SQL query will fetch the records where the time difference exceeds 20 minutes.
Just a note though, you'd want to be on MySQL 5.6 or above to comfortably use TIMESTAMPDIFF
.
Precisely calculating time with respect to timezone
The above line of destiny gives you minute difference at the second-level precision by rounding. Yes, MySQL has got your back!
But what about different timezones?
Scientific way to handle it! It's like telling MySQL, "Hey, consider the timezone before you decide to calculate the time difference."
Creating timeframe comparison with current timestamp
If you want records that are 20 minutes old, well, ask and you shall receive! But remember, CURRENT_TIMESTAMP()
is your secret time-travelling weapon.
Quite magnificent date manipulation
We humans add 20 minutes to the time, and so can MySQL:
Voila! Now you've got '2023-01-01 08:20'.
Working with Unix timestamps
The UNIX_TIMESTAMP()
can help to leap over the hurdle of Unix timestamp:
A superpower that converts Unix timestamps to human-readable dates for comparison with current time.
Dynamic time differences
If you need to find records 20 minutes apart:
Simply use a HAVING clause for evaluating the value directly from the SELECT
statement.
Was this article helpful?