Mak Vasic Mak Vasic - 23 days ago 18
MySQL Question

Intersect between two date intervals

I need to find intersect between to date intervals for example

I have one date

2015-01-01 and 2015-03-01


and second value

2015-01-01 and 2015-01-15


I wanna get results
15
. So how many days of second date is included in first date range?
Any ideas how to do it with MySql?

Answer

In MySQL you can use the following SQL statement to get what you need:

SELECT DATEDIFF(LEAST('2015-03-01 23:59:59','2015-01-15 23:59:59'),GREATEST('2015-01-01 00:00:00','2015-01-01 00:00:00'))+1 AS days;
+------+
| days |
+------+
|   15 |
+------+

This will get the date difference in days using DATEDIFF

Comments