简体   繁体   中英

How to get specific weekday from date period?

I am trying to get count of specific weekday in a month or in a different time period.

In my routine, I have startDate and endDate which indicates the beginning and end of time period in which I am trying to find weekday.

I know how to get day count from start to enddate.

select
   date_part('day',age('2010-04-10', '2010-04-05'));

Gives me an output: 5

This gives me day name:

to_char(current_date, 'day')

Example: 'Monday'.

I have variable called RecurrentWeekDay(has values like 'monday', 'tuesday'.. etc.) and I want to check whether there is weekDay that matches RecurrentWeekDay name ( for example, if RecurrentWeekDay is 'monday', I need to check whether there is monday between startDate and EndDate).

demo:db<>fiddle

You can use generate_series() to generate all dates between the two bounds. Afterwards you can use to_char() to get their week days. With the IN comparator you will get the expected result:

SELECT
    id,
    'Monday' IN (
         SELECT to_char(generate_series(start_date, end_date, interval '1 day'), 'FMDay')
    )
FROM
    mydates

Because your week days always is include, if the date difference is 6 or above, you can optimize to calculate only the date series, that are smaller than 6:

SELECT
    id,
    CASE WHEN end_date - start_date >= 6 THEN true
        ELSE 'Monday' IN (
            SELECT 
                 to_char(
                      generate_series(start_date, end_date, interval '1 day'), 
                      'FMDay'
                 )
        )
    END AS is_in
FROM
    mydates

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