简体   繁体   English

postgres 演员 | 将间隔转换为 iso_8601 格式

[英]postgres cast | convert interval to iso_8601 format

In pg month could be 'mon' or 'month' in php 'mon' is for monday.在 php 中,pg month 可以是 'mon' 或 'month' 'mon' 代表星期一。

myinterval is a interval column on the db. myinterval 是数据库上的间隔列。

how to make pg output如何制作 pg output

`SELECT myinterval FROM table` = 1 year 6 mons

to

`SELECT myinterval FROM table` = P1Y6M

I read about intervalstyle but I'm working with existing code so I can't mess with some lines, with intervalstyle it will change for the whole session我阅读了有关intervalstyle的内容,但我正在使用现有代码,因此我不能弄乱某些行,使用 intervalstyle 它将在整个 session 中发生变化

Sorry for answering this question so late, but I just encountered this same issue in my legacy code base.抱歉这么晚才回答这个问题,但我刚刚在我的旧代码库中遇到了同样的问题。 I solved this by using a transaction and setting the interval style for the duration of the transaction:我通过使用事务并在事务期间设置间隔样式解决了这个问题:

BEGIN;

SET LOCAL intervalstyle = 'iso_8601';
SELECT (INTERVAL '6 years 5 months 4 days 3 hours 2 minutes 1 second')::text;

COMMIT;

This outputs P6Y5M4DT3H2M1S这输出P6Y5M4DT3H2M1S

If I run this directly afterwards:如果我之后直接运行它:

SELECT (INTERVAL '6 years 5 months 4 days 3 hours 2 minutes 1 second')::text;

Then I get 6 years 5 mons 4 days 03:02:01然后我得到6 years 5 mons 4 days 03:02:01

Therefore the session's interval style isn't affected.因此会话的间隔样式不受影响。

You can create a function wrapper to parse the interval:您可以创建一个 function 包装器来解析间隔:

CREATE FUNCTION iso_8601_format(i INTERVAL)
    RETURNS TEXT
    AS $$
        BEGIN
            SET LOCAL intervalstyle = 'iso_8601';
            RETURN i::TEXT;
        END;
    $$ LANGUAGE plpgsql;

and then use it to parse the intervals然后用它来解析区间

postgres=# SELECT iso_8601_format('5 minutes'::INTERVAL);
 iso_8601_format 
----------------
 PT5M
(1 row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM