Get last day of the month with Ruby

last_day_of_the_month = (Date.parse(year_to_process + "-" + (month_to_process.to_i + 1).to_s + "-01") - 1).mday().to_s rescue "31"

The final rescue is due to catch the error when month_to_process is 12.

4 Responses to “Get last day of the month with Ruby”

  1. Philippe Rathe Says:

    Won't (month + 1) returns 13 when december!!!!!????????

  2. hpatoio Says:

    You are right. Just changed the function to works for December too.

  3. Martin Streicher Says:

    Or do this…

    Date.parse( "#{year}-#{ (month + 1) % 12 }-01" ) - 1

  4. alain Says:

    Martin: does not work if month = 11…
    (11+1)%12 = 0…

Leave a Reply

Yes !