Elixir / Phoenix日期从工作日+周数

时间:2017-02-07 05:53:47

标签: date elixir phoenix-framework

是否可以通过提供周数和工作日来获取日期(日,月,年)?基本上我需要查询本周的星期一。

我检查了Erlang,有:erlang.date |> :calendar.day_of_the_week返回工作日。但是,有没有办法扭转这个功能?提供工作日,周数和年份以获得确切的日期?

谢谢

2 个答案:

答案 0 :(得分:1)

  

基本上我需要查询本周的星期一。

您可以将星期日(1)的day_of_the_week与日期(1)的day_of_the_week进行比较,并减去该日期的那几天:

def monday_in_the_week_of(date) do
  from_monday = :calendar.day_of_the_week(date) - 1
  date
  |> :calendar.date_to_gregorian_days
  |> Kernel.-(from_monday)
  |> :calendar.gregorian_days_to_date
end

演示:

defmodule A do
  def monday_in_the_week_of(date) do
    from_monday = :calendar.day_of_the_week(date) - 1
    date
    |> :calendar.date_to_gregorian_days
    |> Kernel.-(from_monday)
    |> :calendar.gregorian_days_to_date
  end
end

for d <- 1..15 do
  date = {2017, 2, d}
  IO.inspect {date, A.monday_in_the_week_of(date)}
end

输出:

{{2017, 2, 1}, {2017, 1, 30}}
{{2017, 2, 2}, {2017, 1, 30}}
{{2017, 2, 3}, {2017, 1, 30}}
{{2017, 2, 4}, {2017, 1, 30}}
{{2017, 2, 5}, {2017, 1, 30}}
{{2017, 2, 6}, {2017, 2, 6}}
{{2017, 2, 7}, {2017, 2, 6}}
{{2017, 2, 8}, {2017, 2, 6}}
{{2017, 2, 9}, {2017, 2, 6}}
{{2017, 2, 10}, {2017, 2, 6}}
{{2017, 2, 11}, {2017, 2, 6}}
{{2017, 2, 12}, {2017, 2, 6}}
{{2017, 2, 13}, {2017, 2, 13}}
{{2017, 2, 14}, {2017, 2, 13}}
{{2017, 2, 15}, {2017, 2, 13}}

答案 1 :(得分:0)

是否可以通过提供星期数和工作日来获取日期(日,月,年)?

也许这样可以工作:

@doc """
iex>get_date(1, 1, 2018)
{:ok, ~D[2018-01-01]}
"""
def get_date(weekday, _week_number, _year)
    when weekday < 1 or weekday > 7,
    do: {:error, "invalid weekday: #{inspect(weekday)}"}

def get_date(_weekday, week_number, _year)
    when week_number < 0 or week_number > 51,
    do: {:error, "invalid week_number: #{inspect(week_number)}"}

def get_date(weekday, week_number, year) do
  case Date.new(year, 1, 1) do
    {:ok, first_day_of_year} ->
      Date.add(first_day_of_year, week_number * 7 + weekday - 1)

    {:error, error} ->
      {:error, error}
  end
end