I have a problem that I am struggling with for a couple of days.
I have a start date {2017, 9, 14} and an end date of {2018, 5, 1}.
What I need is to loop through each day from 2017-9-14 to 2017-5-1:
{2017, 9, 14}
{2017, 9, 15}
{2017, 9, 16}
[...]
{2017, 9, 30}
{2017, 10, 1}
[...]
{2018, 5, 1}
What is a good way to do this in Erlang?
The calendar module in Erlang has a function to convert a date to number of gregorian days starting with year 0: calendar:date_to_gregorian_days/1 and calendar:gregorian_days_to_date/1 to do the reverse. Using these, plus lists:seq, we can generate the list using list comprehension:
1> From = {2017, 9, 14}.
{2017,9,14}
2> To = {2018, 5, 1}.
{2018,5,1}
3> calendar:date_to_gregorian_days(From).
736951
4> calendar:date_to_gregorian_days(To).
737180
5> lists:seq(calendar:date_to_gregorian_days(From), calendar:date_to_gregorian_days(To)).
[736951,736952,736953,736954,736955,736956,736957,736958,
736959,736960,736961,736962,736963,736964,736965,736966,
736967,736968,736969,736970,736971,736972,736973,736974,
736975,736976,736977,736978,736979|...]
6> [calendar:gregorian_days_to_date(X) || X <- lists:seq(calendar:date_to_gregorian_days(From), calendar:date_to_gregorian_days(To))].
[{2017,9,14},
{2017,9,15},
{2017,9,16},
{2017,9,17},
{2017,9,18},
{2017,9,19},
{2017,9,20},
{2017,9,21},
{2017,9,22},
{2017,9,23},
{2017,9,24},
{2017,9,25},
{2017,9,26},
{2017,9,27},
{2017,9,28},
{2017,9,29},
{2017,9,30},
{2017,10,1},
{2017,10,2},
{2017,10,3},
{2017,10,4},
{2017,10,5},
{2017,10,6},
{2017,10,7},
{2017,10,8},
{2017,10,9},
{2017,10,...},
{2017,...},
{...}|...]
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