I have been extensively working with dates recently and found the need to 
create a function between?/3. This function takes first_date, second_date, 
and target_date as inputs and returns a boolean indicating whether 
target_date is between first_date and second_date, inclusive of the 
boundaries if specified.

While the Timex library offers this functionality, the recently added 
Calendar module in Elixir already provides most of the features I need, 
except for this specific function. I believe it would be beneficial to 
include this functionality in the Calendar module.
Proposal

*Function:* Calendar.between?/3

*Description:* This function checks if target_date falls between first_date 
and second_date. By default, the boundaries are exclusive. An optional 
keyword list allows the inclusion of boundaries.

*Example Usage:*
```elixir
Calendar.between?(date_1, date_2, date_3)
```

Returns true if date_3 is between date_1 and date_2, exclusive of date_1 
and date_2.

```elixir

Calendar.between?(date_1, date_2, date_3, inclusive: true)

```

Returns true if date_3 is between date_1 and date_2, inclusive of date_1 
and date_2.

Implementation

Here is a possible implementation of the between?/3 function:

```elixir

defmodule Calendar do
  @moduledoc """
  Provides functionality for working with dates and times.
  """

  @doc """
  Returns true if `target_date` is between `first_date` and `second_date`.

  ## Examples

      iex> Calendar.between?(~D[2024-06-01], ~D[2024-06-30], ~D[2024-06-15])
      true

      iex> Calendar.between?(~D[2024-06-01], ~D[2024-06-30], ~D[2024-06-01])
      false

      iex> Calendar.between?(~D[2024-06-01], ~D[2024-06-30], 
~D[2024-06-01], inclusive: true)
      true

  """
  @spec between?(Date.t(), Date.t(), Date.t(), Keyword.t()) :: boolean()
  def between?(first_date, second_date, target_date, opts \\ []) do
    inclusive = Keyword.get(opts, :inclusive, false)

    if Date.compare(first_date, second_date) == :gt do
      between?(second_date, first_date, target_date, opts)
    else
      case inclusive do
        true ->
          Date.compare(target_date, first_date) != :lt and 
Date.compare(target_date, second_date) != :gt

        false ->
          Date.compare(target_date, first_date) == :gt and 
Date.compare(target_date, second_date) == :lt
      end
    end
  end
end

```

This addition would enhance the Calendar module's functionality by 
providing a straightforward way to determine if a date falls within a 
specified range. 

Best regards

Edwin

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/5eee6d7a-b363-47d6-a64d-7f2e1e8d377an%40googlegroups.com.

Reply via email to