I have a table with information about articles. I have a published_at
column that's a timestamp without time zone
and want to calculate how long ago each article was published, in days.
So if it was published a week ago, I should get back 7
.
Any idea how to go about?
I know Postgres has NOW()
but can I just subtract and then take DAY()
?
Thanks!
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.
PostgreSQL provides a datediff function to users. The datediff means we can return the difference between two dates based on their specified interval. The datediff function plays an important role in the database management system because datediff functions as a calendar and it is very helpful to users.
You can subtract one date from another, the result will be the number of days between the two dates. If one of them is a timestamp, just cast it to a date:
select current_date - published_at::date
from your_table;
If you want to get those that are younger then 7 days, you can use:
select current_date - published_at::date as age_in_days
from your_table
where published_at >= current_date - 7;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With