简体   繁体   English

使用带有时区的 generate_series

[英]Using generate_series with timezone

I'm trying to generate a series that shows the first day of every month in PostgreSQL我正在尝试生成一个系列,在 PostgreSQL 中显示每个月的第一天

select generate_series('2020-01-01T00:00:00+03:00'::timestamptz, '2020-12-31T23:59:59+03:00'::timestamptz, '1 month');

this query returns that result此查询返回该结果

    generate_series     
------------------------
 2019-12-31 21:00:00+00
 2020-01-31 21:00:00+00
 2020-02-29 21:00:00+00
 2020-03-29 21:00:00+00
 2020-04-29 21:00:00+00
 2020-05-29 21:00:00+00
 2020-06-29 21:00:00+00
 2020-07-29 21:00:00+00
 2020-08-29 21:00:00+00
 2020-09-29 21:00:00+00
 2020-10-29 21:00:00+00
 2020-11-29 21:00:00+00
 2020-12-29 21:00:00+00
(13 rows)

but I expect that但我希望

    generate_series     
------------------------
 2019-12-31 21:00:00+00
 2020-01-31 21:00:00+00
 2020-02-29 21:00:00+00
 2020-03-31 21:00:00+00
 2020-04-30 21:00:00+00
 2020-05-31 21:00:00+00
 2020-06-30 21:00:00+00
 2020-07-31 21:00:00+00
 2020-08-31 21:00:00+00
 2020-09-30 21:00:00+00
 2020-10-31 21:00:00+00
 2020-11-30 21:00:00+00
(12 rows)

Where did I go wrong?我在哪里 go 错了?

also there is no problem in using this way使用这种方式也没有问题

select generate_series('2020-01-01T00:00:00'::timestamptz, '2020-12-31T23:59:59'::timestamptz, '1 month');
    generate_series     
------------------------
 2020-01-01 00:00:00+00
 2020-02-01 00:00:00+00
 2020-03-01 00:00:00+00
 2020-04-01 00:00:00+00
 2020-05-01 00:00:00+00
 2020-06-01 00:00:00+00
 2020-07-01 00:00:00+00
 2020-08-01 00:00:00+00
 2020-09-01 00:00:00+00
 2020-10-01 00:00:00+00
 2020-11-01 00:00:00+00
 2020-12-01 00:00:00+00

generate_series works iteratively, so it calculates the next element by adding the step to the precious element. generate_series迭代工作,因此它通过将步骤添加到珍贵元素来计算下一个元素。

The problem is that the calculation is done in your current time zone.问题是计算是在您当前的时区完成的。 The exact meaning of "one month later" unfortunately depends on the time zone...不幸的是,“一个月后”的确切含义取决于时区......

To make this work as expected, change your time tone to match the time zone in the statement:要使这项工作按预期进行,请更改您的时间音以匹配语句中的时区:

SET timezone='+03';

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

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