D
D
Dmitry Bystrov2019-09-12 15:57:47
PostgreSQL
Dmitry Bystrov, 2019-09-12 15:57:47

How to find the intersection of two date ranges?

There are two date ranges: 01.01.2019 - 31.05.2019and 01.03.2019 - 31.12.2019.

How to find their intersection?
As a result, you need to get 01.03.2019 - 31.05.2019:

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2019-09-12
@Rsa97

Intersection condition:
start1 < end2 && start2 < end1 Intersection
area:
[max(start1, start2), min(end1, end2)]

E
Edward, 2019-09-24
@kalter1808

Postgres knows how to work with date ranges.

set datestyle to DMY;
select daterange('01-01-2019'::date,'31-05-2019'::date) * daterange('01-03-2019'::date,'31-12-2019'::date)

This example will return you
More about ranges here:
  • https://postgrespro.ru/docs/postgresql/11/rangetypes
  • https://postgrespro.ru/docs/postgresql/11/function...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question