How to get the number of days in a month?

后端 未结 6 2031
梦毁少年i
梦毁少年i 2020-12-30 23:25

I am trying to get the following in Postgres:

select day_in_month(2);

Expected output:

28

Is there any bu

6条回答
  •  無奈伤痛
    2020-12-30 23:40

    Note that expected output for day_in_month(2) can be 29 because of leap years. You might want to pass a date instead of an int.

    Also, beware of daylight saving : remove the timezone or else some monthes calculations could be wrong (next example in CET / CEST) :

    SELECT  DATE_TRUNC('month', '2016-03-12'::timestamptz) + '1 MONTH'::INTERVAL
          - DATE_TRUNC('month', '2016-03-12'::timestamptz) ;
    ------------------
     30 days 23:00:00
    
    SELECT  DATE_TRUNC('month', '2016-03-12'::timestamp) + '1 MONTH'::INTERVAL
          - DATE_TRUNC('month', '2016-03-12'::timestamp) ;
    ----------
     31 days
    

提交回复
热议问题