sanny Sin
sanny Sin

Reputation: 1555

Get last day of the month in Ruby

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) ?

Upvotes: 60

Views: 56065

Answers (7)

Benjamin Flanders
Benjamin Flanders

Reputation: 1

Here is taking the first and third answers to find the last day of the previous month.

today_c = Date.civil(Date.today.prev_month.year, -1, -1)
p today_c 

Upvotes: 0

akostadinov
akostadinov

Reputation: 18594

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.

Upvotes: 0

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?

Upvotes: 0

Ali Akbar
Ali Akbar

Reputation: 368

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

Upvotes: 0

Netorica
Netorica

Reputation: 19327

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

Upvotes: 115

Jumpers
Jumpers

Reputation: 339

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

Upvotes: 23

Thomas Klemm
Thomas Klemm

Reputation: 10856

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.

Upvotes: 83

Related Questions