开发者

Months ago in ruby

I can't figure out a way (using class definitions) to get months ago. Seconds, days, and minutes are all fine because they're always constants. However since months isn't always constant, i need t开发者_StackOverflow社区o know a way for ruby to know how many days are in the current month.


If your application uses ActiveSupport (e.g. a Rails application), you can use

3.months.ago

to get the current date less 3 months.


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

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

This would 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 instead do:

(Date.today.next_month - Date.today).to_i


Is this what you're looking for? DaysIn(MonthNum)

EDIT 2019-01-20 (for historical purposes)

In the comments, it was reported the link was broken. Thanks to the Internet Archive, here's the original article.

The code block suggested there was:

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

However, as another reader pointed out -- it appears that the desired content was probably months ago, rather than number of days in month.

This question answered the latter part of the question: "i need to know a way for ruby to know how many days are in the current month."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜