Months ago in ruby

I cannot figure out a way (using class definitions) to get months ago. Seconds, days and minutes are all right, because they are always constant. However, since the months are not always constant, I need to know how the ruby ​​finds out how many days are in the current month.

+7
ruby class
source share
3 answers

If your application uses ActiveSupport (for example, a Rails application), you can use

3.months.ago 

to get a current date of less than 3 months.

+7
source share

If you need to know how many days there were between two dates, say today and on the same day of the last month, you can do this:

 (Date.today - Date.today.prev_month).to_i 

This will give you the number of days in the previous month. If you want to know the number of days for the current month, you can:

 (Date.today.next_month - Date.today).to_i 
0
source share

Is this what you are looking for? DaysIn (MonthNum)

EDIT 2019-01-20 (for historical purposes)

The comments said the link was broken. Thanks to the online archive , here is the original article.

The code block suggested that it was:

 def DaysIn(MonthNum) (Date.new(Time.now.year,12,31).to_date<<(12-MonthNum)).day end 

However, as another reader pointed out, it seems that the desired content was probably a few months ago, and not the number of days in a month.

-2
source share

All Articles