At first, you have three cases to consider:
- The beginning of
periodo2
, which I will call p2
, is before or equal to the beginning of the periodo1
, called from now on as p1
. In this case, the answer is the number of days between the beginning of p1
and the end of p1
or p2
, whichever is less.
- The end of
p2
is after or equal to the end of the p1
, in which case the answer is the beginning of p1
or p2
, whichever is greater, subtracted from the end of p1
.
- Both extremes are different, so one must decide which beginning is larger and which end is smaller. The difference of these major beginning and minor end is the number of days in common.
So, in pseudocode, it would be something like:
d1.inicio = periodo1inicio
d1.fim = periodo1fim
d2.inicio = periodo2inicio
d2.fim = periodo2fim
//Caso 1
se d2.inicio = d1.inicio
entao se d1.fim <= d2.fim
entao return DATEDIFF(d1.inicio, d1.fim)
senao return DATEDIFF(d1.inicio, d2.fim)
fim-se
fim-se
//Caso 2
se d2.fim = d1.fim
entao se d1.inicio <= d2.inicio
entao return DATEDIFF(d2.inicio, d1.fim)
senao return DATEDIFF(d1.inicio, d1.fim)
fim-se
fim-se
//Caso 3
se d2.inicio < d1.inicio
entao se d2.fim < d1.fim
entao return DATEDIFF(d1.inicio, d2.fim)
senao return DATEDIFF(d1.inicio, d1.fim)
fim-se
senao se d2.fim < d1.fim
entao return DATEDIFF(d2.inicio, d2.fim)
senao return DATEDIFF(d2.inicio, d1.fim)
fim-se
fim-se
fim-se
I hope you’re not confused.
Do you mean the difference between date 2 and date 1? You can use the mysql DATEDIFF function. You can learn more at: http://www.rafaeltheodoro.com.br/mysql/howto calculatr-differca-de-entre-datas-timestamp-date-ou-time-no-mysql/
– Rafael Withoeft
The
periodo2inicio
is always bigger than theperiodo1inicio
?– Lucas
Not always @Lucas.
– Angelo V. Merlo