Elixir 将日期时间转换为字符串

标签 elixir ecto timex

我有一个原始 sql 查询,它返回一个日期时间字段,我想返回一个带有这些结果的 json。

如果我把返回值我得到一个提示:
(Poison.EncodeError) unable to encode value: {{2017, 3, 21}, {0, 0, 0, 0}}
如果我尝试使用 Timex 将其转换为字符串:
Timex.format!(Ecto.DateTime.from_erl(datetime_field), "%Y-%m-%d %H:%M:%S", :strftime)
我得到:
** (FunctionClauseError) no function clause matching in Ecto.DateTime.from_erl/1
如果我跳过 from_erl部分:
Timex.format!(datetime_field, "%Y-%m-%d %H:%M:%S", :strftime)
我得到:
** (Poison.EncodeError) unable to encode value: {:error, :invalid_date}

最佳答案

获取标准erlang日期时间值需要从第二个元组中删除第四个值(微秒):

datetime = {{2017, 3, 21}, {0, 0, 0, 0}}
{{year, month, day}, {hours, minutes, seconds, _}} = datetime
datetime = {{year, month, day}, {hours, minutes, seconds}}
Poison.encode! Ecto.DateTime.from_erl(datetime)
#=> "\"2017-03-21T00:00:00\""

关于Elixir 将日期时间转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939450/

相关文章:

elixir - 为什么此代码因 Ecto.NoPrimaryKeyValueError 而失败

elixir - 为什么在 Ecto 查询中需要 pin 运算符?

datetime - 设置日期时间毫秒精度 - Elixir

elixir - 生成日期列表

python - Python 中 Timex 字符串到日期时间

elixir - 管道运算符(operator)行为

elixir - Ecto 协会的最佳实践

visual-studio-code - VS Code Elixir F2 "rename symbol"不工作

elixir - 添加一个唯一字段并填充它

elixir - Ecto 表连接