Reputation: 451
I'm currently storing strings formatted like "01/01/1989" (client side validation) for the bday field.
I want to parse out the year and store it as a variable, like this:
@bdayyear = current_user.bday.year
I want that to bring back "1989"
How would I go about doing that?
Upvotes: 0
Views: 204
Reputation: 29318
If the format is always consistent the why not just use the string
"01/01/1989".slice(-4..-1)
"01/01/1989"[-4..-1]
Or
"01/01/1989".split(/\W/).pop
These will all return "1989" without converting it to a date
Upvotes: 0
Reputation: 9752
Convert it into a DateTime
object and you can call year on it
>> DateTime.parse("01/01/1989").year
=> 1989
Upvotes: 0
Reputation: 118261
Just do using #strftime
and ::strptime
:
s = "01/01/1989"
current_user.bday.strptime(s, "%d/%m/%Y").strftime("%Y")
# => "1989"
Upvotes: 1