Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first date of month in postgres

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.

like image 713
Gargoyle Avatar asked Aug 05 '13 23:08

Gargoyle


People also ask

How to get first day of previous month in PostgreSQL?

date_trunc('month', current_date - interval '1' month) will return the 1st day of the previous month and date_trunc('month', current_date) will return the first day of "this" month.

How do I get the first day of year in PostgreSQL?

Use the PostgreSQL DATE_PART() function to retrieve the number of the day of a year from a date/time/datetime/timestamp column. This function takes two arguments. The first argument is the date part (or time part) you want the function to return. In this example, we're using ' doy ', which returns the day of the year.

How to get current month data in PostgreSQL?

Current month: SELECT date_part('month', (SELECT current_timestamp)); Current day: SELECT date_part('day', (SELECT current_timestamp)); Current hour: SELECT date_part('hour', (SELECT current_timestamp)); Current minute: SELECT date_part('minute', (SELECT current_timestamp));

What is Date_trunc in Postgres?

In PostgreSQL, DATE_TRUNC Function is used to truncate a timestamp type or interval type with specific and high level of precision. Syntax: date_trunc('datepart', field) The datepart argument in the above syntax is used to truncate one of the field,below listed field type: millennium. century.


2 Answers

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 

To remove time, cast to date.

select cast(date_trunc('month', current_date) as date) 2013-08-01 

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). 
like image 183
Mike Sherrill 'Cat Recall' Avatar answered Sep 17 '22 22:09

Mike Sherrill 'Cat Recall'


date_trunc() will do it.

SELECT date_trunc('MONTH',now())::DATE; 

http://www.postgresql.org/docs/current/static/functions-datetime.html

like image 23
bma Avatar answered Sep 16 '22 22:09

bma