Get last day of the month in Ruby

后端 未结 6 1567
-上瘾入骨i
-上瘾入骨i 2020-12-12 20:32

I made new object Date.new with args (year, month). After create ruby added 01 number of day to this object by default. Is there any way to add not first day, but last day o

6条回答
  •  攒了一身酷
    2020-12-12 21:16

    This is my Time based solution. I have a personal preference to it compared to Date although the Date solutions proposed above read somehow better.

    reference_time ||= Time.now
    return (Time.new(reference_time.year, (reference_time.month % 12) + 1) - 1).day
    

    btw for December you can see that year is not flipped. But this is irrelevant for the question because december always has 31 day. And for February year does not need flipping. So if you have another use case that needs year to be correct, then make sure to also change year.

提交回复
热议问题