处理DateTime精度> 6在Elixir

时间:2017-12-04 22:22:22

标签: datetime elixir precision

我的代码中有这个功能:

  defp to_date({year, month, day}), do: NaiveDateTime.from_erl!({{year, month, day}, {0, 0, 0}}, {0, 6}) |> NaiveDateTime.to_string()
  defp to_date({{year, month, day}, {hour, min, sec, msec}}) when msec < 1000000,
    do: NaiveDateTime.from_erl!({{year, month, day}, {hour, min, sec}}, {msec, 6}) |> NaiveDateTime.to_string()

  defp to_date(x), do: x

msec > 6-digits时如何处理案件。

使用Tds库从SQLServer datetime2(7)中提取数据的工作正常:

iex(45)> r = Tds.Connection.query(:RMASDB, "select * from users where user_id = 1" , [])
{:ok,
 %Tds.Result{columns: ["user_id", "name", "email", "mobiles", "password", "roles", "active", "reset_required", "last_login", "has_picture", "last_modified", "last_modified_by"], command: nil, num_rows: 1,
  rows: [[1, "Charles Okwuagwu", "charleso@mydomain.com", "mobile1, mobile2", "/eNvuOyr5N6HxgYdz3fK7A==|QHx/sOa3Se0C3ZeLSNtT97SCsuWL11SJeLykms7faGY=", "Administrator", true, false,
    {{2017, 11, 30}, {18, 37, 26, 2690120}}, true, {{2017, 11, 30}, {0, 0, 0, 0}}, 1]]}}

但是使用下面的代码处理日期会抛出此异常:

iex(46)> DB.get(DB.Users, "select * from users where user_id = 1")                      
** (ArgumentError) cannot convert {{2017, 11, 30}, {18, 37, 26}} to naive datetime, reason: :invalid_time
    (elixir) lib/calendar/naive_datetime.ex:549: NaiveDateTime.from_erl!/2
    (rmas) lib/db.ex:34: DB.to_date/1
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (rmas) lib/db.ex:26: anonymous fn/3 in DB._objects/3
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    (rmas) lib/db.ex:17: DB.get/3

源数据值为:{{2017, 11, 30}, {18, 37, 26, 2690120}}

1 个答案:

答案 0 :(得分:1)

datetime2(7)字段存储精度为十分之一微秒。 NaiveDateTime仅支持精度为微秒,因此您可以将值除以10以获得微秒并使用:

defp to_date({{year, month, day}, {hour, min, sec, seven}}),
  do: NaiveDateTime.from_erl!({{year, month, day}, {hour, min, sec}}, {div(seven, 10), 6}) |> NaiveDateTime.to_string()

我们使用div而不是/进行划分,以便结果是整数而不是浮点数。