Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add number of days in postgresql datetime

I have a following table projects.

id title        created_at               claim_window 1  Project One  2012-05-08 13:50:09.924  5 2  Project Two  2012-06-01 13:50:09.924  10 

A) I want to find the deadline with calculation deadline = created_at + claim_window(No. of days).

Something like following.

id title        created_at               claim_window  deadline 1  Project One  2012-05-08 13:50:09.924  5             2012-05-13 13:50:09.924 2  Project Two  2012-06-01 13:50:09.924  10            2012-06-11 13:50:09.924 

B) I also want to find the projects whose deadline is gone

id title        created_at               claim_window  deadline 1  Project One  2012-05-08 13:50:09.924  5             2012-05-13 13:50:09.924 

I try something like following.

SELECT * FROM "projects"  WHERE (DATE_PART('day', now()- created_at) >= (claim_window+1)) 

But for some reason it is not working.

like image 651
Salil Avatar asked Jun 06 '12 07:06

Salil


People also ask

Does Dateadd work in PostgreSQL?

Although PostgreSQL does not provide DATEADD function similar to SQL Server, Sybase or MySQL, you can use datetime arithmetic with interval literals to get the same results.

How do I calculate days between two dates in PostgreSQL?

To count the difference between dates as days in PostgreSQL or Oracle, you simply need to subtract one date from the other, e.g. arrival - departure . But in most cases, what you really want is the number of days from the first date to the second date inclusively.

Does PostgreSQL have DateTime?

PostgreSQL supports the full set of SQL date and time types, shown in Table 8.9. The operations available on these data types are described in Section 9.9.

How do I convert DateTime to date in PostgreSQL?

PostgreSQL Convert DateTime to Date Using EXTRACT() Function EXTRACT() function takes in two arguments, field and source. The field argument specifies the date part, i.e. month, decade, hour, to extract from the DateTime value. The source argument is a value of type TIMESTAMP or INTERVAL.


1 Answers

This will give you the deadline :

select id,          title,        created_at + interval '1' day * claim_window as deadline from projects 

Alternatively the function make_interval can be used:

select id,          title,        created_at + make_interval(days => claim_window) as deadline from projects 

To get all projects where the deadline is over, use:

select * from (   select id,           created_at + interval '1' day * claim_window as deadline   from projects ) t where localtimestamp at time zone 'UTC' > deadline 
like image 175
a_horse_with_no_name Avatar answered Sep 22 '22 08:09

a_horse_with_no_name