有没有办法将日期格式化为仅在 plsql 中显示月份和年份?

Is there a way to format date to only show month and year in plsql?

我无法像这样只输出月份和年份 December 2018 当我创建一个函数来传递日期参数时。

我用下面的测试代码做了一个带有参数的简单函数 return 日期只显示月份和年份。我使用 month 而不是上面描述的 mon,但两者之间存在差距,例如December 2019.

function get_month(p_month DATE DEFAULT sysdate)
return VARCHAR2
is

v_month varchar2(50);

begin

select to_char(trunc(p_month), 'Month yyyy') into v_month from dual;

return v_month;
commit;

end;

理想情况下,我希望月份的全名输出像 to_char(sysdate,'Month DDth, YYYY') 但中间没有日期。

格式字符串中的月份选项似乎生成了带有额外空格的输出,您可以 trim 它们以获得所需的结果。

试试这个:

select trim(to_char(sysdate,'Month'))||' '||to_char(sysdate,'yyyy')
from dual;

这个解释in the documentation:

Oracle uses trailing blank characters and leading zeroes to fill format elements to a constant width. The width is equal to the display width of the largest element for the relevant format model ...

  • The character elements MONTH, MON, DAY, and DY are padded with trailing blanks to the width of the longest full month name ...

还有:

The FM modifier suppresses the above padding in the return value of the TO_CHAR function.

正如@WernfriedDomscheit 在评论中所说,添加 FM 修饰符:

select to_char(trunc(p_month), 'FMMonth yyyy') into v_month from dual;

尽管 trunc() 没有添加任何内容,所以:

select to_char(p_month, 'FMMonth yyyy') into v_month from dual;

或者更简单地说,避免上下文切换,直接赋值:

v_month := to_char(p_month, 'FMMonth yyyy');