Ruby-on-rails – Why can’t I parse a date string saved to a variable in Ruby

activesupportrubyruby-on-rails

I need to run the following code in my Rails app:

ActiveSupport::TimeZone["Central Time (US & Canada)"].parse(game.date).utc.to_date.strftime("%_m/%d")[1..-1]

Where game is @games.each do |game|

But this doesn't work, I get the error, TypeError: no implicit conversion of ActiveSupport::TimeWithZone into String.

However, I can run:

ActiveSupport::TimeZone["Central Time (US & Canada)"].parse("2014-04-11 12am").utc.to_date.strftime("%_m/%d")[1..-1]

which returns "4/11"

How can I use the above code with `game.date' instead of the hard coded string?

EDIT

a Game object looks like the following (from db/seeds.rb):

Game.create(id: 9, date: "2014-04-11 12am", time: "705PM", opponent: "Jacksonville", away: false, event: "friday night fireworks")

EDIT 2

In the rails console when I do game.date it returns:

Fri, 11 Apr 2014 00:00:00 UTC +00:00

so it seems its not a string.

Best Answer

To make what you're trying to do work, you need to convert your date to a string with to_s:

ActiveSupport::TimeZone["Central Time (US & Canada)"].parse(game.date.to_s).utc.to_date.strftime("%_m/%d")[1..-1]

However, you should consider whether this is really what you want to do. As it stands now, this code is taking a date, converting it to a string, parsing the string to get back to the date, then converting it to a string a second time. Are you sure you couldn't get by with something like this?

game.date.strftime(%_m/%d")[1..-1]