Here’s an example of using PostgreSQL to return the number of days in a month, based on a given date.
SELECT
date_part(
'days',
(date_trunc('month', date '2030-07-14') + interval '1 month - 1 day')
);
Result:
31
Here, we used the date_part()
function to return the day number of the last day of the month. We got the last day of the month by using date_trunc()
to truncate the date’s precision to the month, and also by performing some date shifting on the result.
Here’s another example, this time returning the number of days in each month:
SELECT
date_part('days', (date_trunc('month', date '2030-01-14') + interval '1 month - 1 day')) AS "Jan",
date_part('days', (date_trunc('month', date '2030-02-14') + interval '1 month - 1 day')) AS "Feb",
date_part('days', (date_trunc('month', date '2030-03-14') + interval '1 month - 1 day')) AS "Mar",
date_part('days', (date_trunc('month', date '2030-04-14') + interval '1 month - 1 day')) AS "Apr",
date_part('days', (date_trunc('month', date '2030-05-14') + interval '1 month - 1 day')) AS "May",
date_part('days', (date_trunc('month', date '2030-06-14') + interval '1 month - 1 day')) AS "Jun",
date_part('days', (date_trunc('month', date '2030-07-14') + interval '1 month - 1 day')) AS "Jul",
date_part('days', (date_trunc('month', date '2030-08-14') + interval '1 month - 1 day')) AS "Aug",
date_part('days', (date_trunc('month', date '2030-09-14') + interval '1 month - 1 day')) AS "Sep",
date_part('days', (date_trunc('month', date '2030-10-14') + interval '1 month - 1 day')) AS "Oct",
date_part('days', (date_trunc('month', date '2030-11-14') + interval '1 month - 1 day')) AS "Nov",
date_part('days', (date_trunc('month', date '2030-12-14') + interval '1 month - 1 day')) AS "Dec";
Result:
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | 31 | 28 | 31 | 30 | 31 | 30 | 31 | 31 | 30 | 31 | 30 | 31 | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
Be aware that the number of days for February can change depending on whether it’s a leap year or not.