2016-08-12 60 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