2016-08-12 76 views
3

Ecto.DateTime.utc返回当前日期时间。Ecto.Datetime 15分钟前得到

如何在15分钟前创建Ecto.DateTime

+1

有['ago'(https://hexdocs.pm/ecto/Ecto.Query.API.html#ago/2),虽然你不能直接调用它(它意味着要使用的'例如'where子句)。 – evuez

回答

6

使用:erlang.universaltime获取时间(外生使用此为Ecto.DateTime.utc/0),使用:calendar转换成公历秒,减去15 * 60,转换回一个Erlang时间的元组,并投退给Ecto.DateTime

iex(1)> utc = :erlang.universaltime |> :calendar.datetime_to_gregorian_seconds 
63638236105 
iex(2)> fifteen_minutes_ago = (utc - 15 * 60) |> :calendar.gregorian_seconds_to_datetime |> Ecto.DateTime.cast! 
#Ecto.DateTime<2016-08-12 15:33:25> 

编辑:管道可能看起来更好:

:erlang.universaltime 
|> :calendar.datetime_to_gregorian_seconds 
|> Kernel.-(15 * 60) 
|> :calendar.gregorian_seconds_to_datetime 
|> Ecto.DateTime.cast! 
|> IO.inspect 

与以前相同的输出。

+0

它的工作,谢谢!但这里有一个很长的功能链。我们等待较短的实现,也许?附:我并不感到惊讶Timex已经创建;) – asiniy

+0

是的,这很长,但我不认为没有使用另一个库有一个更短的解决方案。我添加了一个管道链,可能看起来好一点。如果有人发布较短的解决方案,这将是非常好的! – Dogbert

+0

没有其他选项... – asiniy