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.
Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.
To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.
Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.
A Date object is created with Date::new , Date::jd , Date::ordinal , Date::commercial , Date::parse , Date::strptime , Date::today , Time#to_date , etc. require 'date' Date. new(2001,2,3) #=> #<Date: 2001-02-03 ...> Date.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With