Find all weekends between two dates

Hi guys,

What’s the simplest way to return all weekends between two calendar:date()?

I’m looking for something like this:

    August 2022       
Su Mo Tu We Th Fr Sa  
    1  2  3  4  5  6  
 7  8  9 10 11 12 13  
14 15 16 17 18 19 20  
21 22 23 24 25 26 27  
28 29 30 31
> weekend:list({2022,8,1}, {2022,8,4}).
[]

> weekend:list({2022,8,4}, {2022,8,11}).
[ {{2022,8,6}, {2022,8,7}} ]

> weekend:list({2022,8,4}, {2022,8,13}).
[ {{2022,8,6}, {2022,8,7}} ]

> weekend:list({2022,8,4}, {2022,8,14}).
[ {{2022,8,6}, {2022,8,7}}, {{2022,8,13}, {2022,8,14}} ]

> weekend:list({2022,8,01}, {2022,8,31}).
[ {{2022,8,6}, {2022,8,7}}, {{2022,8,13}, {2022,8,14}}, {{2022,8,20}, {2022,8,21}}, {{2022,8,27}, {2022,8,28}} ]

> weekend:list({2023,8,1}, {2022,8,1}).
[]

Many thanks.

2 Likes

Naive, probably slow, and not organized code but to give you the idea:

-module(weekends).

-export(list/2).

list(Dt1, Dt2) ->
    DaysBetween = lists:seq(1, calendar:date_to_gregorian_days(Dt2) - calendar:date_to_gregorian_days(Dt1)),
    lists:filter(fun is_weekend/1, [ calendar:gregorian_days_to_date(calendar:date_to_gregorian_days(Dt1) + N) || N <- DaysBetween ]).

is_weekend({Y, M, D}) -> calendar:day_of_the_week(Y, M, D) > 5.
2 Likes

Many thanks.

1 Like

Little fix to the solution.

module(weekends).

-export(list/2).

list(Dt1, Dt2) ->
    DaysBetween = lists:seq(0, calendar:date_to_gregorian_days(Dt2) - calendar:date_to_gregorian_days(Dt1)), %% must start from 0 to cover the Dt1
    lists:filter(fun is_weekend/1, [ calendar:gregorian_days_to_date(calendar:date_to_gregorian_days(Dt1) + N) || N <- DaysBetween ]).

is_weekend({Y, M, D}) -> calendar:day_of_the_week(Y, M, D) > 5.
1 Like