Search code examples
datetimeelixirphoenix-frameworkecto

Is there something like get DaysInMonth for in elixir?


I have searched on Ecto.DateTime, but unfortunately didn't find anything useful. Is there a way to get last day of the month?

I have a query where I load orders from psql, from yesterday (31 July) to today (1 Aug), with today I just use 1, but for the yesterday it can be 31, 30, 29 or 28. Is there a way to know how many days are in the previous month?

Thanks in advance, and any advise appreciated!


Solution

  • There's :calendar.last_day_of_the_month/2 which accepts a year and month as arguments.

    iex(1)> :calendar.last_day_of_the_month(2000, 2)
    29
    iex(2)> :calendar.last_day_of_the_month(2001, 2)
    28
    

    last_day_of_the_month(Year, Month) -> LastDay

    Types:

    Year = year()
    Month = month()
    LastDay = ldom()
    

    Computes the number of days in a month.