MySQL: Get number of Days between two Timestamps
Question by Guest | Last update on 2021-07-19 | Created on 2016-02-09
I would like to find a MySQL way to determine how many days there are between two specified times.
So, I have a timestamp or a date and I would like to compare it to another date in order to calculate the time difference. If possible, it should be considered that months have a varying number of days.
How can I implement that in MySQL?
Related Topics
MySQL: Regular Expressions in MySQL queries
Info | 0 Comments
MySQL: Write current Date or Time into Column
Tutorial | 0 Comments
MySQL: Change minimum word length for full text search
Tip | 1 Comment
MySQL: CSV Export as automatic Download
Tutorial | 0 Comments
Delphi/Lazarus: 3 Ways to round a Number to X Decimal Places
Tutorial | 7 Comments
MySQL: CSV Export as File stored on the Server
Tutorial | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
For this purpose, MySQL is providing the function DATEDIFF(). You can pass 2 dates to this function and you get back the time difference between them.
For example like that:
Here, we are calculating the number of days between January 1, 2021 and January 1, 2031. To ensure that the result will be positive, the first date must be greater than the second one. Otherwise, we will get a negative value.
Of course, we can also directly fetch the date from a table:
In this example, we are reading out the records from the table "tab". In this table, there is also the column "dat" in which the data is stored. Here we would like to get the time difference between this date and January, 1 2021.
Instead of using a fixed date, we can also use the current date using CURDATE():
This query tells us how many days there are between now and January, 1 2031.
If we would like to specify the age of the records in our database, we can also make use of CURDATE() and combine both:
By the way, there is also the function TIMEDIFF() with which we can calculate the difference between two timestamps more exactly.
Last update on 2021-07-19 | Created on 2016-02-11