How to get the last day of month in postgres?

前端 未结 5 1422
醉话见心
醉话见心 2020-12-18 17:47

How to find the last day os the month in postgres? I have a date columns stored as numeric(18) in the format(YYYYMMDD) I am trying it to make it date using

         


        
相关标签:
5条回答
  • 2020-12-18 18:35

    For future searches, Redshift does not accept INTERVAL '1 month'. Instead use dateadd(month, 1, date) as documented here.

    To get the end of the month use: DATEADD(DAY, -1, (DATE_TRUNC('month', DATEADD(MONTH, 1, date))))

    0 讨论(0)
  • 2020-12-18 18:35

    select to_char(date_trunc('month', now() + '01 Months'::interval) - '01 Days'::interval, 'YYYYmmDD'::text)::numeric as end_period_n

    0 讨论(0)
  • 2020-12-18 18:44

    For anybody coming to this question looking for the Postgres way to do this (not using Redshift), here's how you'd do it:

    SELECT (date_trunc('month', '2017-01-05'::date) + interval '1 month' - interval '1 day')::date
    AS end_of_month;
    

    Replacing the '2017-01-05' with whatever date you want to use. You can make this into a function like this:

    create function end_of_month(date)
    returns date as
    $$
    select (date_trunc('month', $1) + interval '1 month' - interval '1 day')::date;
    $$ language 'sql'
    immutable strict;
    
    0 讨论(0)
  • 2020-12-18 18:48

    Okay, so you've got a numeric(18) column containing numbers like 20150118. You can convert that to a date like:

    to_date(your_date_column::text, 'YYYYMMDD')
    

    From a date, you can grab the last day of the month like:

    (date_trunc('month', your_date_column) + 
        interval '1 month' - interval '1 day')::date;
    

    Combined, you'd get:

    select  (date_trunc('month', to_date(act_dt::text, 'YYYYMMDD')) + 
               interval '1 month' - interval '1 day')::date
    from    YourTable;
    

    Example at SQL Fiddle.

    0 讨论(0)
  • 2020-12-18 18:49

    Simply by using the last_day function:

    select last_day(to_date(act_date,'YYYYMMDD'))
    

    PS: Now, i believe that you know that it is very important to choose the right tags for your own question!

    0 讨论(0)
提交回复
热议问题