Alan Coromano
Alan Coromano

Reputation: 26008

How can I add days to Ecto.DateTime?

I have a date-time which I create like this:

Ecto.DateTime.from_erl({{2015, 3, 10}, {0, 0, 0}})

It's a Phoenix app. I want to add days to it with no any additional third-party library. How?

Upvotes: 7

Views: 4590

Answers (4)

Ian Hunter
Ian Hunter

Reputation: 9774

As of at least Elixir 1.5.0, you can use DateTime.add/2 to add days to a date.

# add five days to the current day
DateTime.utc_now |> DateTime.add(5*24*60*60, :second)

Upvotes: 8

Yatender Singh
Yatender Singh

Reputation: 3322

for datetime let say no_of_days is the number of days u want to add.

{{a,b,c},{hh,mm,ss}} = :calendar.universal_time()
{x,y,z} = :calendar.gregorian_days_to_date(:calendar.date_to_gregorian_days({a,b,c}) +no_of_days)
time = Ecto.DateTime.from_erl({{x,y,z},{hh,mm,ss}})

Upvotes: 1

Rizwan Patel
Rizwan Patel

Reputation: 538

Proper elixir syntax

weekday=  :calendar.gregorian_days_to_date(:calendar.date_to_gregorian_days({2011, 7, 14}) - 90)

IO.inspect weekday

{2011, 4, 15}

Upvotes: 1

michalmuskala
michalmuskala

Reputation: 11278

You can use erlang's :calendar module to manipulate dates without additional dependencies.

A standard way of adding days would be to use :calendar.date_to_gregorian_days/1 do the addition and convert back to the tuple format with :calendar.gregorian_days_to_date/1.

Upvotes: 7

Related Questions