本文介绍了在postgres中获取月份的第一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获得与当月的第一天对应的日期类型。基本上我的一个表存储一个日期,但我希望它总是这个月的第一个,所以我试图创建一个触发器,现在得到(),然后用1替换天。
I'm trying to get a 'date' type that corresponds to the first day of the current month. Basically one of my tables stores a date, but I want it to always be the first of the month, so I'm trying to create a trigger that will get now() and then replace the day with a 1.
推荐答案
可以使用表达式 date_trunc('month',current_date)
。用SELECT语句演示。 。 。
You can use the expression date_trunc('month', current_date)
. Demonstrated with a SELECT statement . . .
select date_trunc('month', current_date)
2013-08-01 00:00:00-04
删除时间,转换日期。
select cast(date_trunc('month', current_date) as date)
2013-08-01
如果您确定该列应该始终仅存储一个月的第一个,您还应该使用CHECK约束。
If you're certain that column should always store only the first of a month, you should also use a CHECK constraint.
create table foo (
first_of_month date not null
check (extract (day from first_of_month) = 1)
);
insert into foo (first_of_month) values ('2015-01-01'); --Succeeds
insert into foo (first_of_month) values ('2015-01-02'); --Fails
ERROR: new row for relation "foo" violates check constraint "foo_first_of_month_check"
DETAIL: Failing row contains (2015-01-02).
这篇关于在postgres中获取月份的第一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!