I’m porting some T-SQL stored procs to PL/pgSql and, being very new to PostgreSQL, don’t know what helpful utility functions might be available in the pg community. Is there a set of robust date-math functions that “nearly everybody uses” out there somewhere? I don’t want to quickly cobble together some date-math functions if there’s already a great package out there.
The PostgreSQL date math operators with “natural language” string literal arguments are user-friendly if you’re typing a query and you happen to know the interval:
select now() - interval '1 day'
but if the interval 1 is the result of a calculation involving nested date-math function calls, these string literals are actually not very user-friendly at all, and it would easier to work with a date_add function:
select dateadd(d, {calculation that returns the interval}, now() )
Thanks
Let me give you an example. I want to subtract from an arbitrary date the number of months that have elapsed since 1/1/1970, and then add that number of months to 1/1/1970 to return the first day of the month in which the arbitrary date falls
Or add a month to the first day of this month to get the first day of the next month, then subtract one day to get the last day of this month
Notice in the above example you can add any number of months by multiplying the
interval '1 month'by an integer. You can do that with any interval without manipulating the string'1 month'. So to add or subtract any interval you just:No need for messy string manipulations. You can multiply by fractions also:
To add or subtract days to a
datetype you use an integer: