Why can't I parse a date string saved to a variable in Ruby? Why can't I parse a date string saved to a variable in Ruby? ruby ruby

Why can't I parse a date string saved to a variable in Ruby?


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]


ActiveSupport::TimeZone.parse needs a string and not a Date object example below:

 ActiveSupport::TimeZone["Central Time (US & Canada)"].parse(Date.current.to_s).utc.to_date.strftime("%_m/%d")[1..-1] #=> "4/11" 

so change:

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

to:

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


You can use below string:

As refereed to documentation http://rubyinrails.com/2013/09/strftime-format-time-in-ruby/

game.date.strftime("%Y-%m-%d %I:%M%P")#output=> "2014-04-11 12am"

So in your loop you can use:

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