获得postgres的第一个月份日期

Gar*_*yle 41 postgresql triggers date

我正在尝试获得与当月第一天相对应的"日期"类型.基本上我的一个表存储了一个日期,但我希望它始终是本月的第一个,所以我试图创建一个触发器,它将获得now()然后用1代替日期.

Mik*_*ll' 89

您可以使用表达式date_trunc('month', current_date).使用SELECT语句演示...

select date_trunc('month', current_date)
2013-08-01 00:00:00-04
Run Code Online (Sandbox Code Playgroud)

为了消除时间,施放到目前为止.

select cast(date_trunc('month', current_date) as date)
2013-08-01
Run Code Online (Sandbox Code Playgroud)

如果您确定该列应始终只存储一个月的第一个,那么您还应该使用CHECK约束.

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
Run Code Online (Sandbox Code Playgroud)
ERROR:  new row for relation "foo" violates check constraint "foo_first_of_month_check"
DETAIL:  Failing row contains (2015-01-02).


Nau*_*fal 7

您还可以使用 TO_CHAR 获取该月的第一天:

SELECT TO_CHAR(some_date, 'yyyy-mm-01')::date
Run Code Online (Sandbox Code Playgroud)


小智 6

发现这个可以获取该月的第一天和该月的最后一个日期

select date_trunc('month', current_date-interval '1 year'), date_trunc('month', current_date-interval '1 year')+'1month'::interval-'1day'::interval;
Run Code Online (Sandbox Code Playgroud)