Hommer Smith
Hommer Smith

Reputation: 27862

Ruby - Date ranges (from first of this month to first of next month)

I want to have something like this:

By example: If the first date is 2012-02-01 (YYYY-MM-DD), the next date has to be 2012-03-01. So increment the month. However, if the date is 2012-12-01, the next date has to be 2013-01-01. I have managed to that doing nextMonth=((thisMonth) mod 12)+1 and setting nextYear to thisYear+1 if thisMonth = 12.

My question is: Can I do that easily using the Date library?

Upvotes: 1

Views: 166

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66867

You can use Date#>>:

>> require 'date'
=> true
>> d = Date.new(2012,12,1)
=> #<Date: 2012-12-01 ((2456263j,0s,0n),+0s,2299161j)>
>> d >> 1
=> #<Date: 2013-01-01 ((2456294j,0s,0n),+0s,2299161j)>
>> (d..d>>1)
=> #<Date: 2012-12-01 ((2456263j,0s,0n),+0s,2299161j)>..#<Date: 2013-01-01 ((2456294j,0s,0n),+0s,2299161j)>

If the start date is not the first of the month but you still need the end date to be the first of the following month, you can do this:

>> d = Date.new(2012,12,12)
=> #<Date: 2012-12-12 ((2456274j,0s,0n),+0s,2299161j)>
>> (d>>1) - (d.mday - 1)
=> #<Date: 2013-01-01 ((2456294j,0s,0n),+0s,2299161j)>

Upvotes: 3

Related Questions