How can I add days to Ecto.DateTime?

2019-06-22 08:55发布

问题:

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?

回答1:

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.



回答2:

Proper elixir syntax

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

IO.inspect weekday

{2011, 4, 15}


回答3:

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}})