Get last day of the month in Ruby
RubyDateDatetimeRuby Problem Overview
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 of month that i passed as arg(e.g. 28 if it will be 02month or 31 if it will be 01month) ?
Ruby Solutions
Solution 1 - Ruby
use Date.civil
With Date.civil(y, m, d)
or its alias .new(y, m, d)
, you can create a new Date object. The values for day (d) and month (m) can be negative in which case they count backwards from the end of the year and the end of the month respectively.
=> Date.civil(2010, 02, -1)
=> Sun, 28 Feb 2010
>> Date.civil(2010, -1, -5)
=> Mon, 27 Dec 2010
Solution 2 - Ruby
To get the end of the month you can also use ActiveSupport's helper end_of_month
.
# Require extensions explicitly if you are not in a Rails environment
require 'active_support/core_ext'
p Time.now.utc.end_of_month # => 2013-01-31 23:59:59 UTC
p Date.today.end_of_month # => Thu, 31 Jan 2013
You can find out more on end_of_month in the Rails API Docs.
Solution 3 - Ruby
So I was searching in Google for the same thing here...
I wasn't happy with above so my solution after reading documentation in RUBY-DOC was:
Example to get 10/31/2014
Date.new(2014,10,1).next_month.prev_day
Solution 4 - Ruby
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.
Solution 5 - Ruby
require "date"
def find_last_day_of_month(_date)
if(_date.instance_of? String)
@end_of_the_month = Date.parse(_date.next_month.strftime("%Y-%m-01")) - 1
else if(_date.instance_of? Date)
@end_of_the_month = _date.next_month.strftime("%Y-%m-01") - 1
end
return @end_of_the_month
end
find_last_day_of_month("2018-01-01")
This is another way to find
Solution 6 - Ruby
You can do something like that:
def last_day_of_month?
(Time.zone.now.month + 1.day) > Time.zone.now.month
end
Time.zone.now.day if last_day-of_month?