How to obtain first day of next month in ruby?
I have a date of operation. I want create promissory notes which have got:
day=1
month= the next month of operation_date
year= automatic
Example :
operation_date = 15/11/2010
promissory_note1_date = 1/12/2010
promissory_note2_date = 1/01/2011
promissory_note3_date = 1/02/2011
promissory_note4_date = 1/02/2011
if exist four promissory notes
How could I make it?
PD: Excuse me my syntax
Solution 1:
You can do
require "active_support"
require "active_support/core_ext/date/calculations"
# || require "active_support/all"
Date.today.at_beginning_of_month
#=> Wed, 01 Dec 2010
Date.today.at_beginning_of_month.next_month
#=> Sat, 01 Jan 2011
Date.today.at_beginning_of_month.next_month.next_month
#=> Tue, 01 Feb 2011
And so on...
References
Rails guide 3.0 - 6.1.4 - ActiveSupport - How to Load Core Extensions
Rails guide 3.0 - 6.1.4 - ActiveSupport - Extensions to date
Solution 2:
In case you are not using rails
or do not wish to require active_support
, I found a simpler way without active_support
(Date.today - Date.today.mday + 1) # First day of the current month
=> Thu, 01 Dec 2016
Hope this helps! :-)
Solution 3:
A response to generically obtain N months (in rails)
(Date.today + N.months).at_beginning_of_month
Solution 4:
My solution:
class Time
def start_of_next_month
Time.local(self.year + self.month / 12, self.month % 12 + 1)
end
end
Solution 5:
I am using Ruby 1.8.7
and 1.9.2
with rvm
and in both cases Date.today
results an error:
ruby-1.8.7-p302 > Date.today
NameError: uninitialized constant Date
ruby-1.9.2-p0 > Date.today
NameError: uninitialized constant Object::Date
I thing you should use Time.now
and this link should help you http://pleac.sourceforge.net/pleac_ruby/datesandtimes.html .
I am not sure about availability of at_beginning_of_month
method in ruby but it does exists in RoR.