Reputation: 22254
I'm using Ruby and Ruby on Rails 4.
I'd like get the dates for the 15th and last day of each month for the next two months.
start_date = Time.now
mid_month = start_date.15th.day.of.month
last_day_of_month = start.last.day.of.month
What's the easiest way to accomplish this using Ruby or Rails?
Upvotes: 3
Views: 2845
Reputation: 157
Here's some more:
start_date == Date.today beginning = start_date.beginning_of_month middle = beginning.advance(weeks:2) end = start_date.end_of_month
Looks more human readable.
All these methods available from ActiveSupport class extensions, so you have to include it if not using Rails
Upvotes: 1
Reputation: 96484
For the NEXT two months:
start_date = Date.today
[1..2].each do |month_add|
mid_month = (start_date + month_add.month).beginning_of_month + 14
end_month = (start_date + month_add.month).end_of_month
puts 'Month: #{month_add}'
puts "Mid Month "+mid_month
puts "End Month "+end_month
end
Upvotes: 1
Reputation: 302
I'm not sure if this will work with Rails 4:
start_date = Date.today
# => Wed, 06 Nov 2013
mid_month = (start_date + 1.month).beginning_of_month + 14
# => Sun, 15 Dec 2013
end_month = (start_date + 1.month).end_of_month
# => Tue, 31 Dec 2013
Upvotes: 10
Reputation: 118271
I think something below you are looking for :
require 'date'
d = Date.today
start_date = d-d.mday
p date_15 = start_date.next_day(15)
# => #<Date: 2013-11-15 ((2456612j,0s,0n),+0s,2299161j)>
p date_last = d.next_month - d.mday
# => #<Date: 2013-11-30 ((2456627j,0s,0n),+0s,2299161j)>
Upvotes: 2
Reputation: 13901
There might be some easier way, but this comes to my mind:
require 'Date'
start_date = Date.today
mid_month = Date.new(start_date.year, start_date.month, 15)
end_of_month = Date.new(start_date.year, start_date.month+1, 1)-1
#or
end_of_month = Date.new(start_date.year, start_date.month, 1).next_month.prev_day
Upvotes: 0