How to get the number of days in a given month in Ruby, accounting for year?

If you’re working in Rails, chances are you’ll get hamstrung eventually if you switch among Time, Date, and DateTime, especially when it comes to dealing with UTC/time zones, daylight savings, and the like. My experience has been it’s best to use Time, and stick with it everywhere.

So, assuming you’re using Rails’s Time class, there are two good options, depending on context:

  1. If you have a month m and year y, use the class method on Time:

    days = Time.days_in_month(m, y)
    
  2. If you have a Time object t, cleaner to ask the day number of the last day of the month:

    days = t.end_of_month.day
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)