Junaid Farooq
Junaid Farooq

Reputation: 2608

how to get datetime list using stream in Elixir

how I can get a list of DateTime between 2 datetimes using stream with a specific interval.

I did this

stream = Stream.iterate(starting, &(Calendar.DateTime.add!(&1, 1200)))

1200 is the interval which I want to add to the date each time.

It works fine when I do this.

iex(16)> {:ok, after_seconds, 0, :after} = Calendar.DateTime.diff(ending, starting)
{:ok, 691200, 0, :after}
iex(17)> chunk = after_seconds / 1200 |> trunc
576

576 is the chunk values I need from start datetime till the end datetime

on doing

Enum.take(stream, chunk)

Assuming this is the starting and ending datetime

iex(14)> starting = Calendar.DateTime.from_erl!({{2020, 1, 25},{0, 29, 10}}, "Etc/UTC", {123456, 6}) |> Calendar.DateTime.shift_zone!("Europe/Dublin")
#DateTime<2020-01-25 00:29:10.123456+00:00 GMT Europe/Dublin>
iex(15)> ending = Calendar.DateTime.from_erl!({{2020, 2, 2},{0, 29, 10}}, "Etc/UTC", {123456, 6}) |> Calendar.DateTime.shift_zone!("Europe/Dublin")   
#DateTime<2020-02-02 00:29:10.123456+00:00 GMT Europe/Dublin>

but is very slow. how I can make it faster? what could be the better solution than this?

out of this should be like this

[#DateTime<2020-01-25 00:00:00.123456+00:00 GMT Europe/Dublin>,
 #DateTime<2020-01-25 00:20:00.123456+00:00 GMT Europe/Dublin>,
 #DateTime<2020-01-25 00:40:00.123456+00:00 GMT Europe/Dublin>,
 #DateTime<2020-01-25 01:00:00.123456+00:00 GMT Europe/Dublin>,
 ....
 #DateTime<2020-01-25 23:40:00.123456+00:00 GMT Europe/Dublin>
 ]

Upvotes: 1

Views: 160

Answers (1)

Jason Steinhauser
Jason Steinhauser

Reputation: 325

Do you actually need a DateTime? Or would a Date work just fine? Based on the way that you've phrased your question, I would try starting with a Date, iterating the Stream by using Date.add, and then take however many you need.

Upvotes: 0

Related Questions