Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 859
sanny Sin Avatar asked Jan 02 '13 10:01

sanny Sin


People also ask

How to get last date of month in rails?

end_of_month() Link. Returns a new date/time representing the end of the month. DateTime objects will have a time set to 23:59:59.

How do I get the current date in Ruby?

The today method creates the date object from current date or today date in Ruby language. To get the today date, use Date. today method.


3 Answers

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
like image 117
Netorica Avatar answered Oct 20 '22 22:10

Netorica


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.

like image 23
Thomas Klemm Avatar answered Oct 20 '22 21:10

Thomas Klemm


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

like image 18
Jumpers Avatar answered Oct 20 '22 21:10

Jumpers