sqlpostgresqltime-seriespostgresql-9.1generate-series

Generating time series between two dates in PostgreSQL


I have a query like this that nicely generates a series of dates between 2 given dates:

select date '2004-03-07' + j - i as AllDate 
from generate_series(0, extract(doy from date '2004-03-07')::int - 1) as i,
     generate_series(0, extract(doy from date '2004-08-16')::int - 1) as j

It generates 162 dates between 2004-03-07 and 2004-08-16 and this what I want. The problem with this code is that it wouldn't give the right answer when the two dates are from different years, for example when I try 2007-02-01 and 2008-04-01.

Is there a better solution?


Solution

  • Can be done without conversion to/from int (but to/from timestamp instead)

    SELECT date_trunc('day', dd):: date
    FROM generate_series
            ( '2007-02-01'::timestamp 
            , '2008-04-01'::timestamp
            , '1 day'::interval) dd
            ;