如何从当前日期和Ecto.Date实例中获得多年的差异

时间:2015-09-27 13:13:31

标签: elixir phoenix-framework ecto

假设我有一个public function rules() { return [ ['numbers', 'each', 'rule' => ['integer']], ] } 模型,每个人都将生日字段设置为Person列。

因此,如果我从数据库中检索代表此模型实例的记录,那么从Ecto.Date列中获取此人年龄的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

不确定'最佳方式',但这是 a 方式:

defmodule AgeCalc do
  @spec age(Ecto.Date.t, atom|{integer, integer, integer}) :: integer
  def age(%Ecto.Date{day: d, month: m, year: y}, as_of \\ :now) do
    do_age({y, m, d}, as_of)
  end

  ###########
  # Internals
  ###########
  @doc false
  def do_age(birthday, :now) do
    {today, _time} = :calendar.now_to_datetime(:erlang.now)
    calc_diff(birthday, today)
  end
  def do_age(birthday, date), do: calc_diff(birthday, date)

  @doc false
  def calc_diff({y1, m1, d1}, {y2, m2, d2}) when m2 > m1 or (m2 == m1 and d2 >= d1) do
    y2 - y1
  end
  def calc_diff({y1,_,_}, {y2,_,_}), do: (y2 - y1) - 1
end

用法如下:(今天是2015年9月27日)

iex(1)> AgeCalc.age(%Ecto.Date{day: 27, month: 9, year: 2000})
15
iex(2)> AgeCalc.age(%Ecto.Date{day: 28, month: 9, year: 2000})
14

或者,对于今天以外的其他事项的手动计算:

iex(3)> AgeCalc.age(%Ecto.Date{day: 28, month: 9, year: 2000}, {2034, 12, 25})
34

答案 1 :(得分:0)

I use fragment from Ecto's Query API. I have a user table with a birthday column and am using the following query:

Repo.all(from u in User, select: fragment("age(?)", u.birthday))

The query returns a %Postgrex.Interval{} with fields days, months, and secs. Take months and div by 12 to get the age.

I love Timex but using Postgres' native age function seems cleaner and quicker to me.

答案 2 :(得分:0)

我像这样在长生不老药中做到了

  def calculate_age(dob) when is_binary(dob)
  def calculate_age(dob) when is_binary(dob) do
    today = Date.utc_today()
    dob = Date.from_iso8601! dob
    today.year - dob.year
  end