Reputation: 1415
How do you get the month as an integer from the below code
[email protected] (#<VouchersController:0x007ff453)> t = (Date.today + 5).to_s
=> "2015-12-01"
[email protected] (#<VouchersController:0x007ff453)> t.to_i
=> 2015
[email protected] (#<VouchersController:0x007ff453)>
I can get the year. But how do I get the month as an integer so this returns 12
?
Upvotes: 1
Views: 41
Reputation: 13612
The reason you're getting the year is only that you're converting the string "2015-12-01"
to an integer.
When you use to_i
on a Ruby string, it uses only leading digit characters, then throws away the rest of the string. When it reaches the first -
character, it stops parsing as an integer and returns what it has so far: 2015
.
In order to use the actual functionality of Date
, don't use to_s
to convert the object into a string.
require 'date'
t = Date.today + 5 # => #<Date: 2015-11-30 ((2457357j,0s,0n),+0s,2299161j)>
t.year # => 2015
t.month # => 11
Upvotes: 4