Get the last day of the month in Ruby

I created a new Date.new object with args (year, month). After creating ruby, 01 days are added to this object by default. Is there a way to add not the first day, but the last day of the month that I passed as arg (for example, 28 if it is 02 months or 31 if it is 01 month)?

+45
date ruby datetime
Jan 02 '13 at 10:45
source share
5 answers

use Date.civil

With Date.civil(y, m, d) or its alias .new(y, m, d) you can create a new Date object. Values ​​for day (d) and month (m) can be negative, in which case they are calculated back 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 
+82
Jan 02 '13 at
source share

To get the end of the month, you can also use the ActiveSupport 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 learn more about end_of_month in the Rails API Docs.

+55
Jan 02 '13 at 11:59
source share

So, I searched on Google the same thing here ...

I was dissatisfied with the above, so my solution after reading the documentation in RUBY-DOC :

Production Example 10/31/2014

Date.new(2014,10,1).next_month.prev_day

+11
Oct 10 '14 at 21:28
source share

This is my solution based on Time . I have a personal preference for this compared to Date although the Date suggestions suggested above are somehow better.

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

0
May 18 '18 at 13:48
source share
 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

0
Jun 27 '18 at 12:40
source share



All Articles