在 Postgres 中格式化日期

Format date in Postgres

我有 table,其中 mydate 以以下格式 YYYY-MM-DD 存储在字符变化列中。此 table 中的某些行对于此列是空的。我想按如下方式格式化日期:

SELECT to_char(date mydate, 'FMDay FMDD FMMonth FMYYYY')
  FROM my_table where mydate is not null limit 10;

但我收到以下错误:ERROR: syntax error at or near "mydate" LINE 1: select to_char(date mydate, 'FMDay FMDD FMMonth FMYYY...

为什么会这样。

您需要先将您的 varchar 值转换为日期值,以便您可以将其转换回格式化的 varchar。

您需要删除列名前面的 date 关键字。 date 关键字仅在您编写日期 constants ("literals") 时才需要,而不是在您引用列时。

另外 "empty" 对于 varchar 列 cal 也意味着它包含一个空字符串 (''),因此您还需要在 where 子句中处理它(某事如果您将日期存储在适当的 date 列中,则不需要这样做)

select to_char(to_date(mydate, 'YYYY-MM-DD'), 'FMDay FMDD FMMonth FMYYYY')
from my_table
where mydate is not null
  and mydate <> '' --<< exclude empty strings as well
limit 10;

由于您的值已经是 ISO 格式,您可以使用以下方法稍微缩短此格式:

to_char(mydate::date, 'FMDay FMDD FMMonth FMYYYY')

但是您应该将日期存储在varchar列中。您应该将其存储在 DATE 列中。