10

I have a date in this format {Y,M,D}. Is there any good supporting libraries or, tricks I can use to simply, say subtract three months from this date without running into problem with invalid dates, leap years, etc.

My latest similar use is in MySql where you can type:

Select '2011-05-31' - Interval 3 Month;

which yields '2011-02-28'. I am not interested in how to write this library myself, that is what I would like to avoid.

3 Answers 3

22
1> calendar:gregorian_days_to_date(calendar:date_to_gregorian_days({2011, 7, 14}) - 90).     
{2011,4,15}

http://www.erlang.org/doc/man/calendar.html

1
  • 1
    This works well without downloading a third party module, thanks! Commented Jul 18, 2011 at 10:23
18

Use edate - specifically the shift function.

> edate:shift({2011,5,31}, -3, months).
{2011,2,28}

Under the hood it uses the calendar module, so it correctly deals with all of the corner cases.

0
3

I created a GitHub gist with some useful utilities for this sort of thing. Feel free to steal from it if you want.

https://gist.github.com/104903

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.