Bitwise
Bitwise

Reputation: 8461

Obtaining 3 days ago in Elixir using NaiveDateTime

In RailsLand you can leverage methods that allow you to say things like this Time.now - 1.day or 3.days.ago. For test setup and such these were really nice features of the Rails framework. Does anybody know how to do this with Elixir and Phoenix? I would imagine there is a way but I've had no luck finding anything yet.

I can obviously set the current time like this:

NaiveDateTime.utc_now()

But how can I set it to three days ago from now? or three days from now?

Upvotes: 1

Views: 1598

Answers (2)

silverdr
silverdr

Reputation: 2192

For the typical use case of querying database there is:

https://hexdocs.pm/ecto/Ecto.Query.API.html#module-intervals

which allows somewhat Rails-like constructions. 3.days.ago becomes ago(3, "day") for example.

Upvotes: 0

Igor Drozdov
Igor Drozdov

Reputation: 15075

For this task you can either use NaiveDateTime.add/3 method and add a negative amount of seconds (259200 for 3 days):

NaiveDateTime.utc_now() |> NaiveDateTime.add(-60 * 60 * 24 * 3)

Or timex package:

use Timex
Timex.now |> Timex.shift(days: -3)

Upvotes: 4

Related Questions