如何获取一个月中有多少天?
我试图在 Postgres 中获得以下内容:
select day_in_month(2);
预期输出:
28
Postgres 中是否有任何内置方法可以做到这一点?
I am trying to get the following in Postgres:
select day_in_month(2);
Expected output:
28
Is there any built-in way in Postgres to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
将
NOW()
替换为任何其他日期。Substitute
NOW()
with any other date.使用智能“技巧”从该月的最后一个日期中提取天部分,如Quassnoi 演示的。但它可以更简单/更快一些:
基本原理
extract
是标准 SQL,因此可能更可取,但它在内部解析为与date_part()
相同的函数。 手册:但我们只需要添加一个单个
间隔
。 Postgres 允许同时使用多个时间单位。 手册:ISO 8601 或标准 SQL 格式也被接受。无论哪种方式,再次查看手册:
(输出/显示取决于 设置 < code>IntervalStyle。)
上面的示例使用默认 Postgres 格式:
interval '1 个月 - 1 天'
。这些也是有效的(虽然可读性较差):IS0 8601 格式:
标准 SQL 格式:
都一样。
Using the smart "trick" to extract the day part from the last date of the month, as demonstrated by Quassnoi. But it can be a bit simpler / faster:
Rationale
extract
is standard SQL, so maybe preferable, but it resolves to the same function internally asdate_part()
. The manual:But we only need to add a single
interval
. Postgres allows multiple time units at once. The manual:ISO 8601 or standard SQL format are also accepted. Either way, the manual again:
(Output / display depends on the setting of
IntervalStyle
.)The above example uses default Postgres format:
interval '1 month - 1 day'
. These are also valid (while less readable):IS0 8601 format:
Standard SQL format:
All the same.
请注意,由于闰年,day_in_month(2) 的预期输出可能为 29。您可能想传递日期而不是整数。
另外,请注意夏令时:删除时区,否则某些月份的计算可能会错误(CET / CEST 中的下一个示例):
Note that expected output for day_in_month(2) can be 29 because of leap years. You might want to pass a date instead of an int.
Also, beware of daylight saving : remove the timezone or else some monthes calculations could be wrong (next example in CET / CEST) :
两个时间戳相减将始终产生以天为单位的间隔。我们不会仅仅得到以月或年为单位的答案,因为这些时间段的长度是可变的。
The subtracting two timestamps will always produce an interval in terms of days. We won't just get an answer in terms of months or years, because the length of those time periods is variable.
这也有效。
或者只是:
这两个返回间隔,而不是整数。
This works as well.
Or just:
These two return interval, not integer.
你可以写一个函数:
You can write a function: