to_char() 是一个系统函数,用于将日期、时间戳和数值以指定格式输出。
to_char() 函数在 PostgreSQL 7.0 中被添加。
用法
to_char (timestamp,text) →text
to_char (timestamp with time zone,text) →text
to_char (interval,text) →text
to_char (numeric_type,text) →text
to_char() 将提供的值转换为指定的模板格式;有关详细信息,请参阅 PostgreSQL 文档中 日期/时间格式的模板模式 部分。
变更历史
进行中
- PostgreSQL 15
- 支持
of、tzh和tzm格式模式(提交 9dde8289)
- 支持
- PostgreSQL 11
- 添加了
TZH和TZM格式模式,用于以小时和分钟为单位指定时区相对于UTC的偏移量(提交 11b623dd)
- 添加了
- PostgreSQL 9.6
- 负号("
-")不再被计为时间值的数字(提交 2d87eedc)
- 负号("
- PostgreSQL 9.4
- 添加了时区偏移格式说明符
OF,用于输出时区的 UTC 偏移量(提交 7408c5d2)
- 添加了时区偏移格式说明符
- PostgreSQL 8.4
- 本地化的月份/日期名称从
LC_TIME环境变量派生,而不是LC_MESSAGES(提交 07a56067)
- 本地化的月份/日期名称从
- PostgreSQL 7.2
- 添加了
to_char(interval, text)版本(提交 2a34134b)
- 添加了
- PostgreSQL 7.0
- 已添加(提交 b866d2e2)
示例
使用 to_char() 格式化时间戳的基本示例
postgres=# SELECT to_char(now(), 'YYYY-MM-DD HH24:MI');
to_char
------------------
2021-08-01 10:02
(1 row)
参考资料
- PostgreSQL documentation: Formatting Functions
- PostgreSQL documentation: Template Patterns for Date/Time Formatting
