Eduardo Pereira
Eduardo Pereira

Reputation: 870

What is the right way to compare dates in Ecto

What is the right way to compare dates in range, using the minus operator and comparing if the date is greater than in Ecto ?

  def has_valid_date_range(query) do
    from ct in query,
      where: (ct.end_date - from_now(0, "day")) > 0,
      where: (ct.end_date - from_now(0, "day")) <= ct.due_notice
  end

The result for this query should return all rows where the end_date minus today is greater than 0 and end_date minus today is lower than due_notice

But it returns me an error

** (Ecto.Query.CompileError) ct.end_date() - from_now(0, "day") is not a valid query expression.

Upvotes: 2

Views: 4107

Answers (1)

Dogbert
Dogbert

Reputation: 222168

As we figured out in the comment section, you wanted to select the records whose end_date was after the current time and before due_notice days from the current time. For that, you can use this query:

where: ct.end_date > from_now(0, "day") and
       ct.end_date <= datetime_add(ct.end_date, ct.due_notice, "day")

Upvotes: 5

Related Questions