Antoine Wako Antoine Wako - 3 years ago 156
Ruby Question

Convert date format into another format

I have a hash whose keys are strings expressing dates in format

"%W %Y"
:

{"11 2016"=>255000.0, "12 2016"=>255000.0, "13 2016"=>255000.0, "14 2016"=>255000.0, "15 2016"=>255000.0, "16 2016"=>255000.0, "17 2016"=>255000.0, "18 2016"=>255000.0, "19 2016"=>255000.0, "20 2016"=>255000.0}


I want to convert the keys into Month/Year format to get something like this:

{"March 2016"=>255000.0, "March 2016"=>255000.0, "April 2016"=>255000.0, "April 2016"=>255000.0, "April 2016"=>255000.0, "May 2016"=>255000.0, "May 2016"=>255000.0, "May 2016"=>255000.0, "June 2016"=>255000.0, "June 2016"=>255000.0}


I tried this:

UPDATE

def conv_to_month(hash)
dates_array = []
values = []
hash.each do |k, v|
date = Date.strptime(k, '%W %Y')
newdate = date.strftime('%B %Y')
puts newdate
dates_array << newdate
values << v
end
result = Hash[dates_array.zip(values)]
end


but I get an invalid date error, and I do not understand why.

Answer Source

You can parse the date strings via strptime:

date = Date.strptime('11 2016', '%W %Y')
#=> #<Date: 2016-03-14>

and re-format the resulting date via strftime:

date.strftime('%B %Y')
#=> "March 2016"

But keep in mind that a hash can only contain each key once, so you can't have two keys with "March 2016" (unless you enable compare_by_identity). You might want to use an array instead or – alternatively – use the given hash and format the string using a helper when printing the string (formatting is usually view-related).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download