last_day in PostgreSQL

谁说胖子不能爱 提交于 2021-01-21 11:36:38

问题


The oracle last_day function return the last day of the month. example:

nls_date_format='YYYY-MM-DD H24:MI:SS'
select last_day(sysdate) from dual;
LAST_DAY(SYSDATE)
-------------------
2014-06-30 15:45:43

oracle return the time value as well.

I have tried below sql in PostgreSQL which return the last day of month but time value is "00:00:00".

select (date_trunc('month', now()) + interval '1 month -1 day')::timestamp(0);
         ?column?          
---------------------------
 2014-06-30 00:00:00
(1 row)

the sql return the date correctly but I want date and time like oracle.


回答1:


select (
    date_trunc('month', now())
    + interval '1 month -1 day'
    + now()::time
)::timestamp(0);



回答2:


The function last_day() should do the trick. This function should be found in a extenstion package called "orafce". Containing other functions used in Oracle.

  1. Install the correct version of orafce package (if needed):

    apt-get install postgresql-9.1-orafce
    
  2. SQL:

    Create Extension orafce
    
  3. If error rename orafce--3.0.sql to orafce--3.03.sql or user later version of orafce.

  4. Use the function:

    SELECT last_day('2015-01-01')
    

Works like expected and the result is '2015-01-31'



来源:https://stackoverflow.com/questions/24307073/last-day-in-postgresql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!