简体   繁体   中英

Extract year from current_date

I am working with postgresql and I have a question

How do i extract the year from my current_date. I know how to extract day, month or year from a given date (for example: 2020-10-29). But I need to write a query, that gives certain informations between the beginning of the year and the end of the year. Is there a way to extract the year from my current_date and then to use this as a --select information between start extracted year from current_date and end extracted year from current_date.

Thanks in advance and stay healthy guys!

Usually, you don't want to compare the year only. Instead, you would typically truncate the current date to the beginning of the year.

In Postgres:

where mydate >= date_trunc('year', current_date)

If you want a check on the upper bound as well:

where mydate >= date_trunc('year', current_date)
  and mydate <  date_trunc('year', current_date) + interval '1 year'

If, for some other reason, you need to extract the current year, then use extract() :

extract(year from current_date)

In this example I have simulated the date you are sending/receiving as a c_d. Also, your data is in the table called "test" in this example...

WITH curr_date AS (
    SELECT to_date('2020-05-29', 'yyy-mm-dd') c_d
)
select *
from test
where EXTRACT(YEAR FROM my_date) = (select EXTRACT(YEAR FROM c_d) from curr_date);

Here is a demo:

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM